使用字节流,实现把一个文件里的内容读取出来,写入到另一个文件。
FileInputStream 读文件
FileOutputStream 写文件
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
public class TestFile {
public static void main(String[] args) throws IOException {
//通过简单的程序,把一个文件的内容读取出来,写到另一个文件里(相当于文件拷贝功能)
String srcPath = "/Users/test1.txt";
String destPath = "/Users/test2.txt";
//通过代码实现读取文件
FileInputStream fileInputStream = new FileInputStream(srcPath);
//通过代码实现写文件
FileOutputStream fileOutputStream = new FileOutputStream(destPath);
//读取并写入
while (true){
int ch = fileInputStream.read();
if (ch == -1){
break;
}
fileOutputStream.write(ch);
}
//进行完成记得关闭文件,防止文件资源泄露
fileOutputStream.close();
fileInputStream.close();
}
}
写完文件后一定要记得关闭文件(避免文件泄漏)