文件拷贝
在某一路径下创建txt文件
在相同路径下实现该txt文件的拷贝同时向复制完成文件追加“拷贝完成”字样。
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.RandomAccessFile;
public class sy1 {
public static void method1(String file, String conent) {
BufferedWriter out = null;
try {
out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file, true)));
out.write(conent);
System.out.print("文件追加完成");
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if(out!= null){
out.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args)throws IOException {
String path = "D:\\";
File f = new File(path);
if(!f.exists()){
f.mkdirs();
}
// fileName表示你创建的文件名;为txt类型;
String fileName="text.txt";
File file = new File(f,fileName);
System.out.print("文件创建完成\n");
if(!file.exists()){
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
File file1=new File("D://text.txt");
File file2=new File("D://text1.txt");
//构建输入、输出流
FileInputStream fis=new FileInputStream(file1);
FileOutputStream fos=new FileOutputStream(file2);
int len = fis.available();
byte[] a=new byte[100];
for (int i = 0; i <len; i++) {
System.out.print(fis.read(a));
}
System.out.print("文件复制完成\n");
fos.write(a);
fis.close();
fos.close();
method1("D://text1.txt", "拷贝完成");
}
}