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.
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") );
In java Object is the superclass of all the classes ie. predefined sucs as String or any user defined .
It will accepts any kind of data such as string or any other types contained in the A.txt file.
========================================================================
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);
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:
try (Stream<String> stream = Files.lines(inputFilePath, Charset.forName("UTF-8"))) {
stream.forEach(line -> System.out.println(line));
} catch (IOException e) {
//catch error
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.