Suppose you have a text file named “test.text” which contains these texts below
Apple
Ball
Cat
Now if you want to put those text in a array in java programming you have to write the below code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
import java.io.FileNotFoundException; import java.io.FileReader; import java.util.ArrayList; import java.util.List; import java.util.Scanner; public class tester { public static void main(String[] args) { // TODO Auto-generated method stub Scanner sc = null; try { sc = new Scanner(new FileReader("C:\\Users\\User\\Desktop\\test.txt")); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } List<String> lines = new ArrayList<String>(); while (sc.hasNextLine()) { lines.add(sc.nextLine()); } String[] arr= lines.toArray(new String[0]); System.out.print(arr[1]); //this should print Ball if you work with the content above } } |
Here
1 |
C:\\Users\\User\\Desktop\\test.txt |
is the location of the text file in my pc 🙂