开发者

Java BufferedWriter not creating text file when file doesn't exist

开发者 https://www.devze.com 2022-12-07 22:22 出处:网络
So I\'m trying to use the BufferedWriter Class to create and write to a text file. However, a file is never created, nor is any error generater. However, if I create a text file and specify its path,

So I'm trying to use the BufferedWriter Class to create and write to a text file. However, a file is never created, nor is any error generater. However, if I create a text file and specify its path, it will write to that file; it seems that it just doesn't create files. Any suggestions? Thanks in advance.

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 < c开发者_如何学运维ount*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();
}

}


Made a few changes to the code you provided.

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 = "testCompletetest";
    String fn = "C:\\Users\\13023\\eclipse-workspace\\test\\src\\testprac\\" + storeFile;
    for (int i = 0; i < count*3; i += 3) {
        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] + "\n");  write the strings in the array
    }
    BW.close();
    System.out.println("done");
}
0

精彩评论

暂无评论...
验证码 换一张
取 消