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 fi开发者_StackOverflow社区le, 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?
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:
Files.newReaderSupplier
CharStreams.readLines
Splitter
(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
.)
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
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);
}
}
}
精彩评论