Java 文件读写方式
2020-04-16 本文已影响0人
6ada42df4c4a
1. 以FileInputStream,FileInputStream 字节流的方式进行读写文件操作
@Test
public void test_write_file() throws IOException {
FileInputStream inputStream = new FileInputStream("C:\\Users\\qq\\Desktop\\spa\\test.txt");
coutputStream = new FileOutputStream("C:\\Users\\qq\\Desktop\\spa\\test1.txt");
//定义一次读入或写入多少字节
byte[] bytes = new byte[2];
int n = 0;
//循环取出数据
while ((n = inputStream.read(bytes,0,bytes.length)) != -1){
//转换成字符串
String readString = new String(bytes,0,n,"GBK");
System.out.println(readString);
//写入相关文件
outputStream.write(bytes,0,n);
}
//清除缓存
outputStream.flush();
//关闭流
inputStream.close();
outputStream.close();
}
2. BufferedInputStream、BufferedOutputStream(缓存字节流)使用方式和字节流差不多,但是效率更高(推荐使用)
@Test
public void test_write_file_2() throws IOException {
BufferedInputStream in = new BufferedInputStream(new FileInputStream("C:\\Users\\qq\\Desktop\\spa\\test.txt"));
BufferedOutputStream out =new BufferedOutputStream(new FileOutputStream("C:\\Users\\qq\\Desktop\\spa\\test1.txt"));
byte[] bytes = new byte[3];
int n = 0;
while ((n = in.read(bytes,0, bytes.length)) != -1){
String temps = new String(bytes, 0, n);
System.out.println(temps);
out.write(bytes, 0, n);
}
out.flush();
in.close();
out.close();
}
3. BufferedReader、BufferedWriter(缓存流,提供readLine方法读取一行文本)
@Test
public void test_write_file_3() throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream("C:\\Users\\qq\\Desktop\\spa\\test.txt")));
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("C:\\Users\\qq\\Desktop\\spa\\test1.txt")));
String str = null;
while ((str = in.readLine()) != null){
System.out.println(str);
out.write(str);
out.newLine();
}
out.flush();
out.close();
in.close();
}
4. Reader、PrintWriter(PrintWriter这个很好用,在写数据的同事可以格式化)
//读取文件(字节流)
Reader in = new InputStreamReader(new FileInputStream("d:\\1.txt"),"GBK");
//写入相应的文件
PrintWriter out = new PrintWriter(new FileWriter("d:\\2.txt"));
//读取数据
//循环取出数据
byte[] bytes = new byte[1024];
int len = -1;
while ((len = in.read()) != -1) {
System.out.println(len);
//写入相关文件
out.write(len);
}
//清楚缓存
out.flush();
//关闭流
in.close();
out.close();