简体   繁体   English

无法使用PrintWriter使Java写入文本文件

[英]Can not get java to write to a text file using PrintWriter

Let me preface this by saying that I'm extremely new to java. 让我以说我对Java极其陌生为序。 This is my eighth week in the class and I'm stuck on a project. 这是我上课的第八周,我被困在一个项目上。 Here is what I have so far: 这是我到目前为止的内容:

import java.io.*;


public class Guitar {
// Initialize variables 
boolean isPlaying;
boolean inTune;
char[] guitStrings = {'D', 'G', 'C', 'A'}; // Guitar strings
int numOfStrings = 4; // Number of strings the guitar has.

public void Guitar(){
isPlaying = false; // Guitar is not playing by default.
inTune = false; // Guitar is not tuned by default.
System.out.println("The guitar is not tuned and is not playing.");
}

public void isPlaying(){
    System.out.println("Your guitar is now playing!");
    isPlaying = true; // Set guitar to playing
}
public void inTune(){
    System.out.println("Your guitar is now tuned!");
    inTune = true; // Set guitar to tuned.
}

public void stopPlaying(){
    isPlaying = false; // Set isPlaying to false.
    System.out.println("Your guitar has finished playing!");
}
public void notes(){
    System.out.println("The guitar has played a total of " + numOfStrings + 
            " strings and they are: " + guitStrings[0] + "," + guitStrings[1] + "," 
            + guitStrings[2] + "," + guitStrings[3]);
    }

public static void main(String[] args) throws IOException{
    java.io.File file = new java.io.File("guitartest.txt");
    if(file.exists()){
        System.out.println("File already exists!");
        System.exit(1);
    }

    // Create a file
    java.io.PrintWriter output = new java.io.PrintWriter(file);

    Guitar[] guit = new Guitar[10];   
    for (int i = 0; i < guit.length; i++){
        guit[i] = new Guitar();
        guit[i].Guitar();
        guit[i].inTune();
        guit[i].isPlaying();
        guit[i].notes();
        guit[i].stopPlaying();
    }
}    
}

This program does everything I need it to do, but we have one last step on the project. 该程序可以完成我需要做的所有事情,但是我们在项目上还有最后一步。 I must output this to a text file from the command line. 我必须从命令行将其输出到文本文件。 I've changed the last bit of code to this: 我将最后的代码更改为此:

public static void main(String[] args) throws IOException{
    java.io.File file = new java.io.File("guitartest.txt");
    if (file.exists()){
        System.out.println("This file already exists!");
        System.exit(1);
    }

    // Create a file
    java.io.PrintWriter output = new java.io.PrintWriter(file);

    Guitar[] guit = new Guitar[10];   // Create 10 instruments
    for (int i = 0; i < guit.length; i++){
        output.println(guit[i] = new Guitar());
        output.println(guit[i].Guitar());
        output.println(guit[i].inTune());
        output.println(guit[i].isPlaying());
        output.println(guit[i].notes());
        output.println(guit[i].stopPlaying());
    }
}

This compiles the codes, and displays the results I want in the console, but the text file guitartest.txt is completely blank. 这将编译代码,并在控制台中显示我想要的结果,但是文本文件guitartest.txt完全空白。 I am NOT looking for someone to complete this assignment for me, I'm just looking for any advice or resources you could point me to. 我不是在寻找别人为我完成这项任务,而是在寻找您可以向我提供的任何建议或资源。 Thank you very much! 非常感谢你!

PrintWriter is buffered, that means that the text you're writing to it is stored in its internal buffer before being actually written to the file. PrintWriter被缓冲,这意味着您要写入的文本在实际写入文件之前已存储在其内部缓冲区中。 So you need to call a close() method when you're done writing, so that the PrintWriter object wrote the data to the file and closed it. 因此,完成写入后,您需要调用close()方法,以便PrintWriter对象将数据写入文件并关闭它。

You can also call flush(), this may be useful if you want your data written now but also want to continue using the PrintWriter object. 您也可以调用flush(),如果您想立即写入数据但又想继续使用PrintWriter对象,这可能会很有用。

After you're done writing 写完之后

output.flush();
output.close();

The PrintWriter constructor that accepts a File is implemented as 接受FilePrintWriter构造函数实现为

public PrintWriter(File file) throws FileNotFoundException {
    this(new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file))),
         false);
}

In other words, your outputs are being buffered and need to be flushed from time to time or all in one shot. 换句话说,您的输出正在缓冲中,需要不时刷新或一次刷新。

Call 呼叫

output.flush();

or 要么

output.close();

when you are finished using it. 使用完后。

You probably need to flush the output stream at the end, ie after the for loop in the main() method do 您可能需要在末尾刷新输出流,即在main()方法中的for循环之后执行

output.flush();
output.close();

You can include both of these calls in a try/catch block, for safety: 为了安全起见,可以将这两个调用都包含在try/catch块中:

try {
    output.flush();
    output.close();
} catch (Exception e) {
    e.printStackTrace();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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