16

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();
Paolo Forgia
  • 6,572
  • 8
  • 46
  • 58
heyman
  • 375
  • 2
  • 4
  • 16

5 Answers5

12

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[]{});
dtech
  • 13,741
  • 11
  • 48
  • 73
  • 6
    it work! thank! Also, while((String line = abc.readLine()) not work, It should be String line; while((line = abc.readLine()) then can work:] – heyman Apr 21 '12 at 10:25
4
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[]{});
3

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();
Guillaume Polet
  • 47,259
  • 4
  • 83
  • 117
2

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.

user unknown
  • 35,537
  • 11
  • 75
  • 121
  • That is indeed the way you would do it if only arrays are allowed (or you're programming in C or something) – dtech Apr 21 '12 at 10:15
  • 1
    ALternatively, you could mock what `List` do and increase the size of the array as needed, copying all the items using arrayCopy() and avoiding the costly operation of reading the file twice (although if it is a small File, it won't be significant). – Guillaume Polet Apr 21 '12 at 11:07
2

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();
Paras
  • 240
  • 1
  • 13