Pratik
Pratik

Reputation: 1

I want to read a text file, split it, and store the results in an array

I have a text file which has 10 fields(columns)each separated by a tab.And i have several such rows.I wish to read the text file, split it for every column, using a "tab" delimiter and then storing it in an array of 10 columns and unlimited rows.Can that be done?

Upvotes: 0

Views: 13682

Answers (3)

fftk4323
fftk4323

Reputation: 130

Here is a simple way to load a .txt file and store it into a array for a set amount of lines.

import java.io.*;


public class TestPrograms {

/**
 * @param args the command line arguments
 */
public static void main(String[] args) {
    String conent = new String("da");
    String[] daf = new String[5];//the intiger is the number of lines +1 to
// account for the empty line.
    try{
    String fileName = "Filepath you have to the file";
File file2 = new File(fileName);
    FileInputStream fstream = new FileInputStream(file2);
    BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
    int i = 1;
      while((conent = br.readLine()) != null) {

        daf[i] = conent;
        i++;
    }br.close();
      System.out.println(daf[1]);
      System.out.println(daf[2]);
      System.out.println(daf[3]);
      System.out.println(daf[4]);
    }catch(IOException ioe){
        System.out.print(ioe);
    }

}
}

Upvotes: 0

les2
les2

Reputation: 14479

BufferedReader buf = new BufferedReader(new FileReader(fileName));
String line = null;
List<String[]> rows = new ArrayList<String[]>();
while((line=buf.readLine())!=null) {
   String[] row = line.split("\t");
   rows.add(row);
}
System.out.println(rows.toString()); // rows is a List

// use rows.toArray(...) to convert to array if necessary

Upvotes: 1

Jon Skeet
Jon Skeet

Reputation: 1503509

An array can't have "unlimited rows" - you have to specify the number of elements on construction. You might want to use a List of some description instead, e.g. an ArrayList.

As for the reading and parsing, I'd suggest using Guava, particularly:

(That lets you split the lines as you go... alternatively you could use Files.readLines to get a List<String>, and then process that list separately, again using Splitter.)

Upvotes: 3

Related Questions