在.txt文件中保存整数输入(Java)

时间:2016-03-08 21:50:05

标签: java file input output file-handling

我试图将我输入的整数写入文本文件,但是我编辑代码时,我的记事本将我的整数吐出来作为废话。例如:

输入的整数:java.util.Scanner [delimiters = \ p {javaWhitespace} +] [position = 1] [match valid = true] [need input = false] [source closed = false] [skipped = false]。 ..

我相信我的问题出现在我标有" *"的行中。我该如何解决这个问题?我相信它与" String.valueOf(输入)"有关。线。完整代码链接如下!

for (int i = 0 ; i < 10 ; i++) {
             System.out.printf("Please enter integer %d: ", i+1);
             numbers[i] = input.nextInt();

             {
                 try
                 {
                    *output.format("Integer inputted: %s%n", String.valueOf(input));
                 }
                 catch (FormatterClosedException formatterClosedexception)
                 {
                     System.err.println("Error writing to the file. Terminating.");
                     break;
                 }
                 catch (NoSuchElementException elementException)
                 {
                     System.err.println("Invalid input. Please try again.");
                     input.nextLine();
                 }

http://pastebin.com/yV6dhSMt

1 个答案:

答案 0 :(得分:0)

您可以使用它来写入文件:

PrintWriter writer = new PrintWriter(fileName);
writer.println("1");
writer.println("2");
writer.close();

这是从该文件中读取的:

  String line, newLine;         // Variable to store a line and to check for a new line
  String[] splited;             // Variable to split text
  int lines = 0;                // Variable to check how many lines in a file

  Scanner myReader = new Scanner(new File(fileName));
  BufferedReader bufferedReader = new BufferedReader(new FileReader(fileName));

  Numbers[] numbers = new numbers[2];

  while ((line = bufferedReader.readLine()) != null) {
     lines++;
     for (int i = 1 ; i < 2 ; i++) {
        while (myReader.hasNextLine()) {
           newLine = myReader.nextLine();
           splited = newLine.split(",");
           numbers[i] = Integer.parseInt(splited[i]);
       }
     }
  }

  myReader.close();

我刚刚在这里写了这篇文章,但从我记忆中我就是这样做的。