简体   繁体   中英

how to take the output from command prompt and make a text file out of it using language Java

This is what I have found, but in this code it reads line on what you put in, and I don't want that

I am doing a program called Knight's Tour, and I getting output in Command prompt. All I want to do is to read the lines from Command prompt and store it an output file called knight.txt. Can anyone help me out. Thanks.

try
{
    //create a buffered reader that connects to the console, we use it so we can read lines
    BufferedReader in = new BufferedReader(new InputStreamReader(System.in));

    //read a line from the console
    String lineFromInput = in.readLine();

    //create an print writer for writing to a file
    PrintWriter out = new PrintWriter(new FileWriter("output.txt"));

    //output to the file a line
    out.println(lineFromInput);

    //close the file (VERY IMPORTANT!)
    out.close();
}

catch(IOException e)
{
    System.out.println("Error during reading/writing");
}

You don't need Java for that. Just redirect the output of the game to a file:

game > knight.txt

You may look at this example, it shows how write data into an file, if the file exist it show how to append to the file,

public class FileUtil {

  public void writeLinesToFile(String filename,
                               String[] linesToWrite,
                               boolean appendToFile) {

    PrintWriter pw = null;

    try {

      if (appendToFile) {

        //If the file already exists, start writing at the end of it.
        pw = new PrintWriter(new FileWriter(filename, true));

      }
      else {

        pw = new PrintWriter(new FileWriter(filename));
        //this is equal to:
        //pw = new PrintWriter(new FileWriter(filename, false));

      }

      for (int i = 0; i < linesToWrite.length; i++) {

        pw.println(linesToWrite[i]);

      }
      pw.flush();

    }
    catch (IOException e) {
      e.printStackTrace();
    }
    finally {

      //Close the PrintWriter
      if (pw != null)
        pw.close();

    }

  }

  public static void main(String[] args) {
    FileUtil util = new FileUtil();
    util.writeLinesToFile("myfile.txt", new String[] {"Line 1", 
                                                      "Line 2",
                                                      "Line 3"}, true);
  }
} 

在发布的代码中,只需将lineFromInput更改为要输出到文本文件的任何字符串。

I guess what you are doing is writing the output to file using file operations in java but what you want can be done in an easier way as follows - No code is required for this. The output can be redirected by

file > outputfile

This is independent of java.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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