heyman
heyman

Reputation: 385

Read text file into an array

I want read a text file into an array. How can I do that?

data = new String[lines.size]

I don't want to hard code 10 in the array.

BufferedReader bufferedReader = new BufferedReader(new FileReader(myfile));
String []data;
data = new String[10]; // <= how can I do that? data = new String[lines.size]

for (int i=0; i<lines.size(); i++) {
    data[i] = abc.readLine();
    System.out.println(data[i]);
}
abc.close();

Upvotes: 17

Views: 80218

Answers (5)

File txt = new File("file.txt");
Scanner scan = new Scanner(txt);
ArrayList<String> data = new ArrayList<String>() ;
while(scan.hasNextLine()){
    data.add(scan.nextLine());
}
System.out.println(data);
String[] simpleArray = data.toArray(new String[]{});

Upvotes: 4

Paras
Paras

Reputation: 338

you can do something like this:

  BufferedReader reader = new BufferedReader(new FileReader("file.text"));
    int Counter = 1;
    String line;
    while ((line = reader.readLine()) != null) {
        //read the line 
        Scanner scanner = new Scanner(line);
       //now split line using char you want and save it to array
        for (String token : line.split("@")) {
            //add element to array here 
            System.out.println(token);
        }
    }
    reader.close();

Upvotes: 2

user unknown
user unknown

Reputation: 36259

If you aren't allowed to do it dtechs way, and use an ArrayList, Read it 2 times: First, to get the number of lines to declare the array, and the second time to fill it.

Upvotes: 2

Guillaume Polet
Guillaume Polet

Reputation: 47617

Use a List instead. In the end, if you want, you can convert it back to an String[].

BufferedReader abc = new BufferedReader(new FileReader(myfile));
List<String> data = new ArrayList<String>();
String s;
while((s=abc.readLine())!=null) {
    data.add(s);
    System.out.println(s);
}
abc.close();

Upvotes: 3

dtech
dtech

Reputation: 14060

Use an ArrayList or an other dynamic datastructure:

BufferedReader abc = new BufferedReader(new FileReader(myfile));
List<String> lines = new ArrayList<String>();

while((String line = abc.readLine()) != null) {
    lines.add(line);
    System.out.println(data);
}
abc.close();

// If you want to convert to a String[]
String[] data = lines.toArray(new String[]{});

Upvotes: 13

Related Questions