JAVA IO(二)文件读写

2018-07-15  本文已影响0人  Minstrel_a7ca

File读写

字节流读写

1.直接通过FileInputStream, FileOutputStream
缺点:效率低下,每次都需要底层的系统访问。
关键代码

   //一个复制函数
    static void copy(File srcfile, File dstFile) throws Exception {
        InputStream in = null;
        OutputStream out = null;
        try {
            in = new FileInputStream(srcfile);
            out = new FileOutputStream(dstFile);
            while (in.available() > 0) {
                out.write(in.read());
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } finally {
            if (in != null)
                in.close();
            if (out != null)
                out.close();
        }

2.包装到BufferedInputStreamBufferedInputStream内部维护一个缓存数组,效率高。
只要更改上面代码,包装起来即可。

            in = new BufferedInputStream(new FileInputStream(srcfile));
            out = new BufferedOutputStream(new FileOutputStream(dstFile));

字符流读写

读文件到一个stringBuffer

         StringBuffer str = new StringBuffer(); 
           char[] buf = new char[1024]; 
           FileReader f = new FileReader("file"); 
           while(f.read(buf)>0){ 
               str.append(buf); 
           } 
           str.toString(); 

读文件到一个stringBuffer,指定编码

通过InputStreamReader指定编码

        StringgBuilder sb = new StringBuilder();
            //指定编码为”GBK“
            in = new InputStreamReader(new FileInputStream(file), "GBK");
            char[] buf = new char[1024];
            while (in.read(buf) > 0) {
                sb.append(buf);
            }
            System.out.println(sb);

把一个String写到文件1.txt

Writer out = new FileWriter("1.txt");
out.write(s);
//"utf-8"编码写
out = new OutputStreamWriter(new FileOutputStream("1.txt"), "UTF-8");
out.write(s);
上一篇 下一篇

猜你喜欢

热点阅读