目录
一、字节流
注意: FileOutputStream(File file) 、 FileOutputStream(String name) 或FileOutputStream(File file, false)创建FileOutputStream对象时会创建一个新的空文件;如果使用FileOutputStream(File file, true)创建FileOutputStream对象,则只在第一次执行时创建一个新的空文件。
代码如下:
File a = new File("D:\\a.mp3");
File b = new File ("D:\\b.mp3");
FileInputStream inputStream = new FileInputStream(a);
FileOutputStream outputStream = new FileOutputStream(b);
byte [] car = new byte[1024];
int length = 0;
while ((length = inputStream.read(car))!=-1){
outputStream.write(car,0,length);
}
二、字符流
注意: FileWriter (File file) 、 FileWriter (String fileName) 或FileWriter (File file, false)创建FileWriter对象时会创建一个新的空文件;如果使用FileWriter (File file, true)创建FileWriter对象,则只在第一次执行时创建一个新的空文件。
代码示例:
FileReader reader = new FileReader("D:\\1.txt");
FileWriter writer = new FileWriter("F:\\1.txt");
int data;
while ((data = reader.read())!=-1){
writer.write(data);
}
writer.flush();
writer.close();
reader.close();
三、缓冲流
代码示例:
FileInputStream fileInputStream = new FileInputStream("D:\\1.mp3");
BufferedInputStream bufferedInputStream = new BufferedInputStream(fileInputStream);
FileOutputStream fileOutputStream = new FileOutputStream("f:\\1.mp3");
BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(fileOutputStream);
byte [] car = new byte[1024];
int length = 0;
while ((length = bufferedInputStream.read(car))!=-1){
bufferedOutputStream.write(car,0,length);
}
bufferedOutputStream.flush();
bufferedOutputStream.close();
bufferedInputStream.close();
FileReader reader = new FileReader("D:\\1.txt");
BufferedReader bufferedReader = new BufferedReader(reader);
FileWriter writer = new FileWriter("D:\\1.txt");
BufferedWriter bufferedWriter = new BufferedWriter(writer);
char [] car = new char[1024];
int length;
while ((length = bufferedReader.read(car))!=-1){
System.out.println(11);
bufferedWriter.write(car,0,length);
}
bufferedWriter.flush();
bufferedWriter.close();
bufferedReader.close();
四、转换流
字符文件可以使用字节流读取,字节流转换为字符流,解决字符流乱码现象
代码示例:
FileInputStream inputStream = new FileInputStream("D:\\1.txt");
InputStreamReader reader = new InputStreamReader(inputStream,"GBK");
FileOutputStream outputStream = new FileOutputStream("F:\\1.txt");
OutputStreamWriter writer = new OutputStreamWriter(outputStream,"GBK");
char [] car = new char[1024];
int length;
while ((length = reader.read(car))!=-1){
System.out.println(11);
writer.write(car,0,length);
}
writer.flush();
writer.close();
reader.close();