[英]Copy text from one file to another using Java
The content of Testing.txt
is not getting copied in Testing2.txt
. 的内容Testing.txt
是没有得到复制在Testing2.txt
。 If I store some random data in Testing2.txt
it gets erased when i run the java project instead of copying the content of Testing.txt
. 如果我在Testing2.txt
存储一些随机数据,则在我运行Java项目而不是复制Testing.txt
的内容时,它将被擦除。
Here is the link to the tutorial I am practicing . 这是我正在练习的教程的链接。 The steps are strictly followed and I have named the project, package and classes as it is given. 严格遵循这些步骤,并按给出的名称命名了项目,程序包和类。
Why is the content not getting copied? 为什么没有复制内容?
Both in reading and writing there is missing: 在阅读和写作方面都缺少:
} finally {
writer.close();
}
As: 如:
public String readTextFile(String fileName) {
String returnValue = "";
FileReader file;
String line = "";
try {
file = new FileReader(fileName);
BufferedReader reader = new BufferedReader(file);
try {
while ((line = reader.readLine()) != null) {
returnValue += line + "\n";
}
} finally {
reader.close();
}
} catch (FileNotFoundException e) {
throw new RuntimeException("File not found");
} catch (IOException e) {
throw new RuntimeException("IO Error occured");
}
return returnValue;
}
public void writeTextFile(String fileName, String s) {
FileWriter output;
try {
output = new FileWriter(fileName);
BufferedWriter writer = new BufferedWriter(output);
writer.write(s);
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
操作后关闭作家和读者,它可以正常工作。
You FileWriter
object overrides the data written to your file. FileWriter
对象将覆盖写入文件的数据。 Try using this constructor, which appends the data: 尝试使用此构造函数,该构造函数会附加数据:
FileWriter
public FileWriter(String fileName,
boolean append)
throws IOException
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.