Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java adding file contents to array list

Tags:

java

Hi i am new to Java working with files. I have got a text file called banking.txt located in C: but when i try put its content into an ArrayList and print it prints out nothing. Is the file path i am using incorrect or is it something different?

import java.util.ArrayList;
import java.util.Scanner;
import java.io.*;

public class FileP {
    public static void main(String[] args) throws FileNotFoundException {
        Scanner read = new Scanner(new File("C:\\banking.txt"));
        ArrayList<String> myList = new ArrayList<String>();
        while(read.hasNextLine()) {
            myList.add(read.nextLine());
        }
        System.out.println(myList);
    }
}
like image 970
Blue Avatar asked Nov 28 '25 01:11

Blue


1 Answers

Try to use InputStream

    import java.io.BufferedReader;
    import java.io.FileInputStream;
    import java.io.IOException;
    import java.util.ArrayList;
    import java.io.InputStream;
    import java.io.InputStreamReader;

    public class FileP {

      public static void main(String[] args) throws IOException {

        ArrayList<String> myList = new ArrayList<String>();
        InputStream is = new FileInputStream("C:\\banking.txt");
        BufferedReader buf = new BufferedReader(new InputStreamReader(is));
        String line = buf.readLine();
        StringBuilder sb = new StringBuilder();
        while (line != null)

        {
          myList.add(line);
          line = buf.readLine();
        }

       System.out.println("myList : " + myList);
      }
    }
like image 161
MadukaJ Avatar answered Nov 29 '25 14:11

MadukaJ