[英]write a java file from a string (The string content from a text file by reading it line by line)
我想将字符串的内容保存到 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) {
// [...]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.