tags:

views:

131

answers:

4

How would I read a .txt file in Java and put every line in an array when every lines contains integers, strings, and doubles? And every line has different amounts of words/numbers.

I'm a complete noob in Java so sorry if this question is a bit stupid.

Thanks

+1  A: 

Your question is not very clear, so I'll only answer for the "read" part :

List<String> lines = new ArrayList<String>();
BufferedReader br = new BufferedReader(new FileReader("fileName"));
String line = br.readLine();
while (line != null)
{
    lines.add(line);
    line = br.readLine();
}
Valentin Rocher
you forgot br.close()
Arne Burmeister
+3  A: 

Try the Scanner class which no one knows about but can do almost anything with text.

To get a reader for a file, use

File file = new File ("...path...");
String encoding = "...."; // Encoding of your file
Reader reader = new BufferedReader (new InputStreamReader (
    new FileInputStream (file), encoding));

... use reader ...

reader.close ();

You should really specify the encoding or else you will get strange results when you encounter umlauts, Unicode and the like.

Aaron Digulla
+1 for pointing out Scanner. I hadn't heard about it before. Interesting class.
JasCav
+1  A: 

Easiest option is to simply use the Apache Commons IO JAR and import the org.apache.commons.io.FileUtils class. There are many possibilities when using this class, but the most obvious would be as follows;

List<String> lines = FileUtils.readLines(new File("untitled.txt"));

It's that easy.

"Don't reinvent the wheel."

Alasdair