Как я могу открыть txt файл для чтения чисел, разделенных входами или пробелами в список массивов?
Как открыть txt файл и прочитать числа в java
Ответ 1
Прочитайте файл, проанализируйте каждую строку в целое и сохраните в списке:
List<Integer> list = new ArrayList<Integer>();
File file = new File("file.txt");
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader(file));
String text = null;
while ((text = reader.readLine()) != null) {
list.add(Integer.parseInt(text));
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
}
}
//print out the list
System.out.println(list);
Ответ 2
Ниже представлена более короткая альтернатива:
Path filePath = Paths.get("file.txt");
Scanner scanner = new Scanner(filePath);
List<Integer> integers = new ArrayList<>();
while (scanner.hasNext()) {
if (scanner.hasNextInt()) {
integers.add(scanner.nextInt());
} else {
scanner.next();
}
}
Сканер разбивает свой вход на токены, используя шаблон разделителя, который по умолчанию соответствует пробелу. Хотя разделитель по умолчанию является пробелом, он успешно обнаружил все целые числа, разделенные новым символом строки.
Ответ 3
try{
BufferedReader br = new BufferedReader(new FileReader("textfile.txt"));
String strLine;
//Read File Line By Line
while ((strLine = br.readLine()) != null) {
// Print the content on the console
System.out.println (strLine);
}
//Close the input stream
in.close();
}catch (Exception e){//Catch exception if any
System.err.println("Error: " + e.getMessage());
}finally{
in.close();
}
Это будет читаться по строкам,
Если нет. преобразуются с помощью новой строки char. то вместо
System.out.println (strLine);
У вас может быть
try{
int i = Integer.parseInt(strLine);
}catch(NumberFormatException npe){
//do something
}
Если он разделен пробелами, то
try{
String noInStringArr[] = strLine.split(" ");
//then you can parse it to Int as above
}catch(NumberFormatException npe){
//do something
}
Ответ 4
Хорошие новости в java 8 мы можем сделать это в одной строке
List<Integer> ints = Files.lines(Paths.get(fileName))
.map(Integer::parseInt)
.collect(Collectors.toList());
Ответ 5
File file = new File("file.txt");
Scanner scanner = new Scanner(file);
List<Integer> integers = new ArrayList<>();
while (scanner.hasNext()) {
if (scanner.hasNextInt()) {
integers.add(scanner.nextInt());
} else {
scanner.next();
}
}
System.out.println(integers);