如何在现有文件中附加字符串?(How to append a string in an existing file?)
优质
小牛编辑
126浏览
2023-12-01
问题描述 (Problem Description)
如何将一个文件复制到另一个文件?
解决方案 (Solution)
此示例显示如何使用BufferedWriter类的读写方法将一个文件的内容复制到另一个文件中。
import java.io.*;
public class Main {
public static void main(String[] args) throws Exception {
BufferedWriter out1 = new BufferedWriter(new FileWriter("srcfile"));
out1.write("string to be copied\n");
out1.close();
InputStream in = new FileInputStream(new File("srcfile"));
OutputStream out = new FileOutputStream(new File("destnfile"));
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
in.close();
out.close();
BufferedReader in1 = new BufferedReader(new FileReader("destnfile"));
String str;
while ((str = in1.readLine()) != null) {
System.out.println(str);
}
in.close();
}
}
结果 (Result)
上面的代码示例将产生以下结果。
string to be copied
以下是将一个文件复制到java中的另一个文件的另一个示例示例
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
public class CopyExample {
public static void main(String[] args) {
FileInputStream ins = null;
FileOutputStream outs = null;
try {
File infile =new File("C:\\Users\\xnip7\\Desktop\\abc.txt");
File outfile =new File("C:\\Users\\xnip7\\Desktop\\bbc.txt");
ins = new FileInputStream(infile);
outs = new FileOutputStream(outfile);
byte[] buffer = new byte[1024];
int length;
while ((length = ins.read(buffer)) > 0) {
outs.write(buffer, 0, length);
}
ins.close();
outs.close();
System.out.println("File copied successfully!!");
} catch(IOException ioe) {
ioe.printStackTrace();
}
}
}
上面的代码示例将产生以下结果。
File copied successfully!!