简体   繁体   English

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

[英]write a java file from a string (The string content from a text file by reading it line by line)

I want to save the content of the string to a Java file.我想将字符串的内容保存到 Java 文件中。 The content of the string "sttr" is read from a text file line by line.从文本文件中逐行读取字符串“sttr”的内容。 When I run the code I got correct output but when I try to write the content to a Java file I got only one line.当我运行代码时,我得到了正确的输出,但是当我尝试将内容写入 Java 文件时,我只有一行。 Code:代码:

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());
}

Don't recreate your BufferedWriter at each time, do it once outside the loop.不要每次都重新创建您的 BufferedWriter,在循环外执行一次。 Otherwise, it will erase the content of the file.否则,它将擦除文件的内容。

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM