一、原理
在windows系统中,我们通过“ctrl+c”以及“ctrl+v”就能进行文件的复制,但是如果要通过java代码编写,则需要进行两个过程,即文件的读取以及文件的写入。
二、需要用到的类与方法
1.读取文件
使用FileInputStream类,读取文件,构造方法如下:
使用的方法:
.read()
2.写入文件
使用FileOutputStream类,写入文件,构造方法如下:
使用的方法:
.write()
三、代码的编写
1.文件读取
读取D盘下123.txt文件的内容。
public class Demo2 {
public static void main(String[] args) throws Exception {
FileInputStream fl = new FileInputStream("d:\\123.txt");
byte[] by = new byte[fl.available()];
fl.read(by);
String str = new String(by);
System.out.println(str);
}
}
2.文件写入
将“但使龙城飞将在,不教胡马度阴山”写入D盘456.txt文件中。
public class Demo2 {
public static void main(String[] args) throws Exception {
FileOutputStream os = new FileOutputStream("d:\\456.txt");
String str = "但使龙城飞将在,不教胡马度阴山";
os.write(str.getBytes());
}
}
3.复制
将以上文件的读取和写入结合起来,就能完成文件的复制了。
public class Demo2 {
public static void main(String[] args) throws Exception {
FileInputStream fl = new FileInputStream("d:\\123.txt");
byte[] by = new byte[fl.available()];
fl.read(by);
FileOutputStream os = new FileOutputStream("d:\\789.txt");
os.write(by);
}
}