从文件中读取整数并用新文件重写它们

时间:2015-11-17 20:28:41

标签: java

我试图从文件中提取整数并将其写入某些情况,以免我不得不复制和粘贴这么多。这就是我所拥有的:

public class PullFrom {
    public static void main(String[] args) throws IOException {
        Scanner input = new Scanner(new File("PullFrom.txt"));
        BufferedWriter out = new BufferedWriter(new FileWriter("OutPutFile.txt", true));
        int ID;

        while (input.hasNextLine()) {
            ID = input.nextInt();

            for (int i = 0; i < 1; i++) {
                try {
                    out.write("case " + ID + ":");
                    out.newLine();
                    out.write("setRandomWalk(false);");
                    out.newLine();
                    out.write("break;");
                    out.newLine();
                } catch (IOException e) {
                    System.out.println("Cannot Do It");
                    e.printStackTrace();
                }
            }
        }
        out.close();
        input.close();
    }
}

在Eclipse中,我在控制台中得到了这个:

Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at reader.PullFrom.main(PullFrom.java:17)

此错误在控制台中重复多次。和我的#34;不能做它&#34;文本。

这是我&#34; PullFrom.txt&#34;的一个例子。文件:

524
1988
7823
6723

最后,程序在我的输出文件中生成了什么:

case 524:
setRandomWalk(false);
break;

这似乎是正确的,但它只打印出第一个int ..

1 个答案:

答案 0 :(得分:4)

您在循环的每次迭代中调用out.close()。将调用out.close()置于while循环块之外。

修改:更改后,您应该尝试在while循环表达式中检查hasNextLine()hasNextInt()。如果仍然产生异常,你可以将你的调用包装在try / catch中,如果触发了catch,则退出循环。

while(input.hasNextLine() && input.hasNextInt()) {
  try {
     ...
  } catch (NoSuchElementException e) {
     break;
  }
}
相关问题