Java outputting to text file?

后端 未结 5 697
悲哀的现实
悲哀的现实 2021-01-28 06:59

So I am having troubles printing to output. I understand the concept, but when it comes to this problem its kinda weird. I\'ve tried different print lines and all of them give m

相关标签:
5条回答
  • 2021-01-28 07:37

    Try this:

    PrintWriter output =  new PrintWriter("test.txt");
    output.println(data[0]);      //this is where you call the println
    for (int i = 0; i < data.length; i++) {
        output.printf( ", %d", data[i]);
        output.flush();
    }
    
    0 讨论(0)
  • 2021-01-28 07:40

    To make it a new line for each output loop it and add "\n" to each line you write or you can convert to string and edit String format to whatever you want. You can add a comma if you want

    string.format()
    
    0 讨论(0)
  • 2021-01-28 07:52

    Cause of problem: In your code, everytime you call text(), you are replacing existing file, without updating or appending new data to it.

    Refer this SO question. You can write printWriter as

    PrintWriter output = new PrintWriter(new BufferedWriter(new FileWriter("test.txt", true)));
    

    I have tested on local, Try this code.

    public void text() {
        try {
            // Adding data to existing file without replacing it.
            PrintWriter output = new PrintWriter(new BufferedWriter(new FileWriter("test.txt", true)));
            output.print(data[0]);
            for (int i = 1; i < data.length; i++) {
                output.printf(", %d", data[i]);
            }
            output.print("\n"); // Added next line in the file
            output.flush();
            output.close(); // closing PrintWriter.
        } catch (Exception ex) {
            // log your exception.
        }
    }
    
    0 讨论(0)
  • 2021-01-28 07:53

    Try this :

    public void text() {
            try {
                PrintWriter output = new PrintWriter("test.txt");
                output.println(data[0]);
                for (int i = 0; i < data.length; i++) {
                    if (i != (data.length - 1)) {
                        output.printf("%d, ", data[i]);
                    } else {
                        output.printf("%d", data[i]);
                    }
                    output.flush();
                }
            } catch (Exception ex) {
    
            }
    
        }
    
    0 讨论(0)
  • 2021-01-28 07:53

    try do in this way

    public void text() {
        try {
           PrintWriter output =  new PrintWriter("test.txt");
    
           for (int i = 0; i < data.length; i++) {
               if(i > 0){
                   output.print(",");
               }
    
               output.print(data[i]);
               output.flush();     
           }   
        } catch (Exception ex) {
        }
    }
    
    0 讨论(0)
提交回复
热议问题