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);
}
}
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);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With