-5
    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.

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
  • 4
    `it also throws some exception while compiling this code`. Maybe that's a piece of information you should add to the question – NeplatnyUdaj Mar 26 '19 at 12:46
  • Possible duplicate of [Java reading a file into an ArrayList?](https://stackoverflow.com/questions/5343689/java-reading-a-file-into-an-arraylist) – Akash Mar 26 '19 at 12:49
  • Write the logic into a method. Variables can be set global at the class if you want to. – LenglBoy Mar 26 '19 at 12:53

4 Answers4

3

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.

J. Doe
  • 88
  • 7
0

The Correct Syntax for Scanner : Scanner s = new Scanner(new File("A.txt") );

Object

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);


    } 
}
Akash
  • 425
  • 2
  • 7
  • 21
-1

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);
}
lolo
  • 17,392
  • 9
  • 25
  • 49
-1

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
}