使用IO流实现文件复制
在学习了一些文件相关知识和io流的一些知识以后,写了个小测试类来实现文件和文件夹的创建和文件复制。
public class Copy {
public static void main(String[] args) {
try {
//创建文件并输入内容
File file = new File("D:\\temp\\temp.txt");
boolean newFile = file.createNewFile();
FileOutputStream outputStream = new FileOutputStream("D:\\temp\\temp.txt");
outputStream.write("hello world".getBytes());
//创建文件夹并在文件夹中创建文件
File file1 = new File("D:\\temp\\temp");
if (!file1.exists()){
file1.mkdir();
}
File file2 = new File("D:\\temp\\temp\\temp.txt");
if (!file1.exists()){
file1.createNewFile();
}
//读出旧文件内容,写进新文件中
FileOutputStream outputStream1 = new FileOutputStream("D:\\temp\\temp\\temp.txt");
FileInputStream fileInputStream = new FileInputStream("D:\\temp\\temp.txt");
int ch;
while((ch=fileInputStream.read()) != -1){
System.out.println((char)ch);
outputStream1.write(ch);
}
fileInputStream.close();
outputStream1.close();
outputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
在这个过程中也遇到了一些问题,因此记录下来,以供以后避坑。
首先,一开始,我在复制文件这一块是这么写的:
while((fileInputStream.read()) != -1){
System.out.println((char)fileInputStream.read());
outputStream1.write(fileInputStream.read());
}
这样就导致读出来的文件内容只有一半,写入的和读出的还不一样。
经过一番尝试改成了这样,问题得到了解决。
int ch;
while((ch=fileInputStream.read()) != -1){
System.out.println((char)ch);
outputStream1.write(ch);
}
原因在于fileInputStream.read()方法读取数据时,会使缓冲区数据减少一位,并返回一个经过编码的int型数字,由于while里面调用了一次方法,write里又调用了一次方法,所以导致打印出来的字符串和写入新文件的字符串都只有一半。问题得到解决。