首页 > 其他分享 >读写文件方法大全

读写文件方法大全

时间:2023-05-16 12:32:40浏览次数:21  
标签:文件 String 读写 fileName try catch new 大全


Java指定编码读写文件(UTF-8) [url]http://gaofeihang.blog.163.com/blog/static/8450828520098241202798/[/url]
读取

import java.io.BufferedReader;  
    import java.io.FileInputStream;  
    import java.io.InputStreamReader;  

    String FileContent = ""; // 文件很长的话建议使用StringBuffer 
    try { 
        FileInputStream fis = new FileInputStream("d:\\input.txt"); 
        InputStreamReader isr = new InputStreamReader(fis, "UTF-8"); 
        BufferedReader br = new BufferedReader(isr); 
        String line = null; 
        while ((line = br.readLine()) != null) { 
            FileContent += line; 
            FileContent += "\r\n"; // 补上换行符 
        } 
    } catch (Exception e) { 
        e.printStackTrace(); 
    }



写入


import java.io.FileOutputStream; 
    import java.io.OutputStreamWriter; 

    String FileContent = "文件内容"; 
    try { 
        FileOutputStream fos = new FileOutputStream("d:\\output.txt"); 
        OutputStreamWriter osw = new OutputStreamWriter(fos, "UTF-8"); 
        osw.write(FileContent); 
        osw.flush(); 
    } catch (Exception e) { 
        e.printStackTrace(); 
    }




1、按字节读取文件内容


2、按字符读取文件内容


3、按行读取文件内容


4、随机读取文件内容


5、将内容追加到文件尾部



7. JAVA复制文件最快的算法 [url]http://mazhihui.iteye.com/blog/1552309[/url]


public class ReadFromFile {
    /**
     * 以字节为单位读取文件,常用于读二进制文件,如图片、声音、影像等文件。
     */
    public static void readFileByBytes(String fileName) {
        File file = new File(fileName);
        InputStream in = null;
        try {
            System.out.println("以字节为单位读取文件内容,一次读一个字节:");
            // 一次读一个字节
            in = new FileInputStream(file);
            int tempbyte;
            while ((tempbyte = in.read()) != -1) {
                System.out.write(tempbyte);
            }
            in.close();
        } catch (IOException e) {
            e.printStackTrace();
            return;
        }
        try {
            System.out.println("以字节为单位读取文件内容,一次读多个字节:");
            // 一次读多个字节
            byte[] tempbytes = new byte[100];
            int byteread = 0;
            in = new FileInputStream(fileName);
            ReadFromFile.showAvailableBytes(in);
            // 读入多个字节到字节数组中,byteread为一次读入的字节数
            while ((byteread = in.read(tempbytes)) != -1) {
                System.out.write(tempbytes, 0, byteread);
            }
        } catch (Exception e1) {
            e1.printStackTrace();
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e1) {
                }
            }
        }
    }

    /**
     * 以字符为单位读取文件,常用于读文本,数字等类型的文件
     */
    public static void readFileByChars(String fileName) {
        File file = new File(fileName);
        Reader reader = null;
        try {
            System.out.println("以字符为单位读取文件内容,一次读一个字节:");
            // 一次读一个字符
            reader = new InputStreamReader(new FileInputStream(file));
            int tempchar;
            while ((tempchar = reader.read()) != -1) {
                // 对于windows下,\r\n这两个字符在一起时,表示一个换行。
                // 但如果这两个字符分开显示时,会换两次行。
                // 因此,屏蔽掉\r,或者屏蔽\n。否则,将会多出很多空行。
                if (((char) tempchar) != '\r') {
                    System.out.print((char) tempchar);
                }
            }
            reader.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            System.out.println("以字符为单位读取文件内容,一次读多个字节:");
            // 一次读多个字符
            char[] tempchars = new char[30];
            int charread = 0;
            reader = new InputStreamReader(new FileInputStream(fileName));
            // 读入多个字符到字符数组中,charread为一次读取字符数
            while ((charread = reader.read(tempchars)) != -1) {
                // 同样屏蔽掉\r不显示
                if ((charread == tempchars.length)
                        && (tempchars[tempchars.length - 1] != '\r')) {
                    System.out.print(tempchars);
                } else {
                    for (int i = 0; i < charread; i++) {
                        if (tempchars[i] == '\r') {
                            continue;
                        } else {
                            System.out.print(tempchars[i]);
                        }
                    }
                }
            }

        } catch (Exception e1) {
            e1.printStackTrace();
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e1) {
                }
            }
        }
    }

    /**
     * 以行为单位读取文件,常用于读面向行的格式化文件
     */
    public static void readFileByLines(String fileName) {
        File file = new File(fileName);
        BufferedReader reader = null;
        try {
            System.out.println("以行为单位读取文件内容,一次读一整行:");
            reader = new BufferedReader(new FileReader(file));
            String tempString = null;
            int line = 1;
            // 一次读入一行,直到读入null为文件结束
            while ((tempString = reader.readLine()) != null) {
                // 显示行号
                System.out.println("line " + line + ": " + tempString);
                line++;
            }
            reader.close();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e1) {
                }
            }
        }
    }

    /**
     * 随机读取文件内容
     */
    public static void readFileByRandomAccess(String fileName) {
        RandomAccessFile randomFile = null;
        try {
            System.out.println("随机读取一段文件内容:");
            // 打开一个随机访问文件流,按只读方式
            randomFile = new RandomAccessFile(fileName, "r");
            // 文件长度,字节数
            long fileLength = randomFile.length();
            // 读文件的起始位置
            int beginIndex = (fileLength > 4) ? 4 : 0;
            // 将读文件的开始位置移到beginIndex位置。
            randomFile.seek(beginIndex);
            byte[] bytes = new byte[10];
            int byteread = 0;
            // 一次读10个字节,如果文件内容不足10个字节,则读剩下的字节。
            // 将一次读取的字节数赋给byteread
            while ((byteread = randomFile.read(bytes)) != -1) {
                System.out.write(bytes, 0, byteread);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (randomFile != null) {
                try {
                    randomFile.close();
                } catch (IOException e1) {
                }
            }
        }
    }

    /**
     * 显示输入流中还剩的字节数
     */
    private static void showAvailableBytes(InputStream in) {
        try {
            System.out.println("当前字节输入流中的字节数为:" + in.available());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        String fileName = "C:/temp/newTemp.txt";
        ReadFromFile.readFileByBytes(fileName);
        ReadFromFile.readFileByChars(fileName);
        ReadFromFile.readFileByLines(fileName);
        ReadFromFile.readFileByRandomAccess(fileName);
    }
}




将内容追加到文件尾部


public class AppendToFile {
    /**
     * A方法追加文件:使用RandomAccessFile
     */
    public static void appendMethodA(String fileName, String content) {
        try {
            // 打开一个随机访问文件流,按读写方式
            RandomAccessFile randomFile = new RandomAccessFile(fileName, "rw");
            // 文件长度,字节数
            long fileLength = randomFile.length();
            //将写文件指针移到文件尾。
            randomFile.seek(fileLength);
            randomFile.writeBytes(content);
            randomFile.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * B方法追加文件:使用FileWriter
     */
    public static void appendMethodB(String fileName, String content) {
        try {
            //打开一个写文件器,构造函数中的第二个参数true表示以追加形式写文件
            FileWriter writer = new FileWriter(fileName, true);
            writer.write(content);
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        String fileName = "C:/temp/newTemp.txt";
        String content = "new append!";
        //按方法A追加文件
        AppendToFile.appendMethodA(fileName, content);
        AppendToFile.appendMethodA(fileName, "append end. \n");
        //显示文件内容
        ReadFromFile.readFileByLines(fileName);
        //按方法B追加文件
        AppendToFile.appendMethodB(fileName, content);
        AppendToFile.appendMethodB(fileName, "append end. \n");
        //显示文件内容
        ReadFromFile.readFileByLines(fileName);
    }
}

标签:文件,String,读写,fileName,try,catch,new,大全
From: https://blog.51cto.com/u_3871599/6283431

相关文章

  • Java实现文件拷贝的4种方法.
    第一种方法:古老的方式publicstaticlongforJava(Filef1,Filef2)throwsException{longtime=newDate().getTime();intlength=2097152;FileInputStreamin=newFileInputStream(f1);FileOutputStreamout=newFileOutputStream(f2);byte[]buffer=newbyte......
  • 12槽2极有刷直流电机工程文件及性能波形
    12槽2极有刷直流电机工程文件及性能波形ID:49199662468470218......
  • 传输文件测试一下群晖2.5G网卡性能表现如何,实操验证
    各位观众好,欢迎来到黑菌的博客网站,淘宝同名,欢迎咨询!1、A文件所在的机器是N5105的群晖上B机器也安装了群晖,接了一个2.5G的网卡2、使用同步软件CloudSync,传输远程文件夹ESXI中的文件到本地的FTP文件夹 3、效果看图偶有波动是文件有大小,不是一份文件基本上稳定在260上下......
  • Linux 文件上传下载的几种方式
    虚拟终端软件中的rz和sz我们使用虚拟终端软件,如Xshell、SecureCRT或PuTTY来连接远程服务器后,可以使用rz或sz来上传下载文件rz命令使用rz命令可以上传本地文件到远程服务器。运行该命令会弹出一个文件选择窗口,从本地选择文件上传到Linux服务器sz命令将选定的......
  • Spring中实现文件上传
    一些问题:springmvc文件上传,使用它的MultipartHttpServletRequest,tomcat中正常,resion中报错[url]http://zhupan.iteye.com/blog/26427[/url]实现图片上传用户必须能够上传图片,因此需要文件上传的功能。比较常见的文件上传组件有CommonsFileUpload(htt......
  • Matlab保存数据到csv文件的方法分享
    ✅作者简介:热爱科研的算法开发者,Python、Matlab项目可交流、沟通、学习。......
  • java获取目录下文件名称
    1.package2.import3.import4.import5.6./**7.*读取目录及子目录下指定文件名的路径,返回一个List8.*/9.10.publicclass11.privatestaticLoggerlogger=Logger.getLogger(FileViewer.class);12.13./**14.*@parampath15.......
  • 如何分发Teamcenter的jar文件?
    1.将jar包拷贝到TC的Portal文件夹下的plugins文件夹中,例如:D:\Siemens\Teamcenter14\portal\plugins 2.删除用户文件中的Teamcenter临时文件,例如:C:\Users\zyq\Teamcenter 3.运行TC注册bat文件:D:\Siemens\Teamcenter14\portal\registry\genregxml.bat  ......
  • python 中 pyfaidx 模块统计fasta文件每一条染色体的长度
     001、python版本和pip版本a、python版本[root@PC1pip]#python--versionPython3.11.3 b、pip版本[[email protected]]#pip--versionpip23.1.2from/usr/local/lib/python3.11/site-packages/pip(python3.11) 002、利用pip安装 pyfaidx模块......
  • pathlib模块--面向对象的文件系统路径标准
    1pathlib中的path类获取当前工作目录Path.cwd()注意P是大写这个和os.getcwd()结果很类似获取一个当前目录下的path对象获取当前系统的home路径根据给定参数的匹配模式,返回所有匹配到的文件注意glob()返回的是一个生成器,是看不到具体内容的,可用sorted()或者list()或......