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.包装到BufferedInputStream
,BufferedInputStream
内部维护一个缓存数组,效率高。
只要更改上面代码,包装起来即可。
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);