从文件读取直到EOF

时间:2014-04-25 03:07:57

标签: java

我有一个txt文件,现在我想修改它,所以我可以让它通过

整个系列' 10101010'每行而不仅仅是' 1'每行...... 我有一个字符串,将添加到数组列表中并使用字符串

执行
'
  1
  0
  0
  1
  1
  0
  0
  1

'


Scanner getInput = new Scanner(System.in);
        String fileName = getInput.nextLine();

        File file = new File(fileName + ".txt");
        Scanner scanner = new Scanner(file);
        while (scanner.hasNextLine()) {
            stringData += scanner.nextLine();
        }

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

            list.add((Integer.valueOf(stringData.substring(i, i + 1))));

            System.out.println(list.get(i));

        }

1 个答案:

答案 0 :(得分:0)

我相信你过度考虑了你的实施,跳过List<Integer> -

更简单
public static void main(String[] args) throws FileNotFoundException {
  Scanner getInput = new Scanner(System.in);
  String fileName = getInput.nextLine();

  File file = new File(fileName + ".txt");
  Scanner scanner = new Scanner(file);
  StringBuilder sb = new StringBuilder();
  while (scanner.hasNextInt()) {     // Check for an int. With a Scanner there is no
                                     // need for getting the input one line at a time.
    sb.append(scanner.nextInt());    // Append it (as an int) to the StringBuilder.
  }
  System.out.println(sb.toString()); // Print it on one line.
}

我测试了这个,

$ pwd
/home/efrisch
$ cat input.txt
1
0
1
0
1

输出

/home/efrisch/input
10101