gpt4 book ai didi

java - 从字符串写入java文件(通过逐行读取文本文件中的字符串内容)

转载 作者:行者123 更新时间:2023-12-01 12:24:46 25 4
gpt4 key购买 nike

我想将字符串的内容保存到Java文件中。字符串“sttr”的内容是从文本文件中逐行读取的。当我运行代码时,我得到了正确的输出,但是当我尝试将内容写入 Java 文件时,我只得到一行。代码:

String content = " test ";   
String content1 = "test01";
//read text file line by line

try {
FileInputStream fstream = new FileInputStream("E:\\test\\myfile.txt");
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));

String strLine;
String sttr ;
while ((strLine = br.readLine()) != null) {
sttr = strLine;
System.out.println(content+sttr+content1);

File file = new File("E:/test/output.java");
// if file doesnt exists, then create it
if (!file.exists()) {
file.createNewFile();
}

FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);

//bw.write(content);
bw.write(content+sttr+content1);
//bw.write(content1);
//bw.close();
//System.out.println("Done");
}
}
catch (Exception e) { //Catch exception if any
System.err.println("Error: " + e.getMessage());
}

最佳答案

不要每次都重新创建 BufferedWriter,而是在循环外执行一次。否则,它将删除文件的内容。

File file = new File("E:/test/output.java");
// if file doesnt exists, then create it
if (!file.exists()) {
file.createNewFile();
}
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);

String strLine;
String sttr ;
while ((strLine = br.readLine()) != null) {
// [...]

关于java - 从字符串写入java文件(通过逐行读取文本文件中的字符串内容),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26450801/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com