0

这就是我发现的,但在这段代码中,它读取的是你输入的内容,我不希望这样

我正在做一个名为 Knight's Tour 的程序,并在命令提示符下获得输出。我要做的就是从命令提示符中读取这些行并将其存储为一个名为 knight.txt 的输出文件。谁能帮我吗。谢谢。

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");
}
4

4 回答 4

5

你不需要Java。只需将游戏的输出重定向到一个文件:

game > knight.txt
于 2012-09-19T03:57:48.737 回答
0

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

于 2012-09-19T04:25:07.297 回答
0

你可以看看这个例子,它展示了如何将数据写入文件,如果文件存在,它展示了如何追加到文件中,

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);
  }
} 
于 2012-09-19T04:16:37.053 回答
0

我猜你正在做的是使用 java 中的文件操作将输出写入文件,但你想要的可以更简单的方式完成,如下所示 - 不需要代码。输出可以通过以下方式重定向

file > outputfile

这与java无关。

于 2012-09-19T04:38:24.080 回答