【问题标题】:Java BufferedWriter not creating text file when file doesn't exist当文件不存在时,Java BufferedWriter 不创建文本文件
【发布时间】:2022-12-07 09:24:22
【问题描述】:

所以我正在尝试使用 BufferedWriter 类来创建和写入文本文件。但是,永远不会创建文件,也不会产生任何错误。但是,如果我创建一个文本文件并指定其路径,它将写入该文件;似乎它只是不创建文件。有什么建议么?提前致谢。

public class test3 {
public static void main(String[] args) throws IOException {
    int ctr = 1;
    int count = 10;
    Random r = new Random();
    String[] textData = new String[count*3];
    
    String storeFile = "testComplete";
    String fn = "C:\\Users\\13023\\eclipse-workspace\\test\\src\\testprac\\" + storeFile;
    for (int i = 0; i < count*3; i++) {
        textData[i] = "Test";
        textData[i+1] = "Tes";
        textData[i+2] = "T";
        ctr++;
        i = i + 2;
    }
    
    BufferedWriter BW = new BufferedWriter(new FileWriter(fn));
    int j = 0;
    for (String s:  textData) {
        BW.write(textData[j] + "\n");
        System.out.println("done");
    }
    BW.close();
}

}

【问题讨论】:

    标签: java text-files filewriter bufferedwriter


    【解决方案1】:

    对您提供的代码进行了一些更改。

    import java.io.BufferedWriter;
    import java.io.FileWriter;
    import java.io.IOException;
    public class test3 {
    public static void main(String[] args) throws IOException {
        int ctr = 1;
        int count = 10;
        // Random r = new Random();     // not used by program, maybe it will later
        String[] textData = new String[count*3];
        
        String storeFile = "testComplete";
        String fn = "C:\Users\13023\eclipse-workspace\test\src\testprac\" + storeFile;
        for (int i = 0; i < count*3; i++) {
            textData[i] = "Test";
            textData[i+1] = "Tes";
            textData[i+2] = "T";
            ctr++;
            i = i + 2;
        }
        
        BufferedWriter BW = new BufferedWriter(new FileWriter(fn));
        //int j = 0;   not used.
        for (String s:  textData) {
            // ******* modified  *******
            BW.write(s);    // textData[j] + "
    ");  write the strings in the array
        }
        BW.close();
        System.out.println("done");
    }
    

    【讨论】:

    • 我尝试运行它,但同样的问题 - 没有创建文件
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多