[英]How to read file into an Arraylist and print the ArrayList in Java
import java.io.*;
import java.util.*;
class List{
Scanner s = new Scanner("A.txt");
ArrayList<String> list = new ArrayList<String>();
while (s.hasNext()){
list.add(s.next());
}
s.close();
}
}
In my current working directory I have a file A.txt which contains some data, but I am unable to read and print it in the array list.在我当前的工作目录中,我有一个包含一些数据的文件 A.txt,但我无法在数组列表中读取和打印它。
It also throws some exception while compiling this code.它在编译这段代码时也会抛出一些异常。
You cant compile because there is no method.您无法编译,因为没有方法。 You got a Class here and try to implement your code in the class, not in a method.
你在这里有一个类,并尝试在类中实现你的代码,而不是在方法中。
The Correct Syntax for Scanner : Scanner s = new Scanner(new File("A.txt") );扫描仪的正确语法: Scanner s = new Scanner(new File("A.txt") );
In java Object is the superclass of all the classes ie.
在 Java 中 Object 是所有类的超类,即。 predefined sucs as String or any user defined .
预定义 sucs 为 String 或任何用户定义的 .
It will accepts any kind of data such as string or any other types contained in the A.txt file.
它将接受任何类型的数据,例如字符串或 A.txt 文件中包含的任何其他类型。
======================================================================== ================================================== ======================
import java.io.*;
import java.util.*;
class B{
public static void main(String aregs[]) throws FileNotFoundException {
Scanner s = new Scanner(new File("A.txt") );
ArrayList<Object> list = new ArrayList<Object>();
while(s.hasNext()) {
list.add(s.next());
}
System.out.println(list);
}
}
For example例如
into array成阵列
arr = Files.lines(path)
.map(item -> Arrays.stream(item.split(" ")).mapToInt(Integer::parseInt).toArray())
.toArray(int[][]::new);
print打印
public static void printArray(int[][] array) {
if (array == null) return;
Arrays.stream(array).map(Arrays::toString).forEach(System.out::println);
}
If you are using Java 8 you can use Streams:如果您使用的是 Java 8,则可以使用 Streams:
try (Stream<String> stream = Files.lines(inputFilePath, Charset.forName("UTF-8"))) {
stream.forEach(line -> System.out.println(line));
} catch (IOException e) {
//catch error
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.