3

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

Eight
  • 4,126
  • 5
  • 27
  • 51

8 Answers8

12

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
  • 310,263
  • 103
  • 579
  • 794
  • +1 for pointing out Scanner. I hadn't heard about it before. Interesting class. – JasCav Jan 12 '10 at 14:40
  • 1
    "No one knows about Scanner". atleast held true for me. The scanner can also be used as: Scanner sc = new Scanner(new File("fileName")); //any idea why not to use it this way? – Syed Ali Apr 16 '12 at 10:38
  • @sttaq: Because that uses the default encoding. Never use the default encoding when reading data. Always find out what the input is or specify what encoding your code accepts; in either way, nail it down to something specific. – Aaron Digulla Oct 08 '15 at 07:36
9

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
  • 242
  • 1
  • 2
  • 6
4

The best approach to read a file in Java is to open in, read line by line and process it and close the strea

// Open the file
FileInputStream fstream = new FileInputStream("textfile.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(fstream));

String strLine;

//Read File Line By Line
while ((strLine = br.readLine()) != null)   {
  // Print the content on the console - do what you want to do
  System.out.println (strLine);
}

//Close the input stream
fstream.close();

To learn more about how to read file in Java, check out the article.

Johnny
  • 12,661
  • 14
  • 70
  • 112
3

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
  • 11,521
  • 44
  • 59
2

Common used:

    String line = null;
    File file = new File( "readme.txt" );

    FileReader fr = null;
    try
    {
        fr = new FileReader( file );
    } 
    catch (FileNotFoundException e) 
    {  
        System.out.println( "File doesn't exists" );
        e.printStackTrace();
    }
    BufferedReader br = new BufferedReader( fr );

    try
    {
        while( (line = br.readLine()) != null )
    {
        System.out.println( line );
    }
Andrew Barber
  • 38,454
  • 20
  • 92
  • 120
Kamil
  • 41
  • 2
  • 1
    Welcome to Stack Overflow! Thanks for your post! Please do not use signatures/taglines in your posts. Your user box counts as your signature, and you can use your profile to post any information about yourself you like. [FAQ on signatures/taglines](http://stackoverflow.com/faq#signatures) Especially, please do not include your website URL, as your posts could be flagged as spam. – Andrew Barber Mar 12 '13 at 21:38
  • @Kamil After adding java import.io.* to the top and including the class, this worked fine for me except that the output to the cmd window has a space between each alphabet. How to avoid the spaces in the output. – Unnikrishnan Jan 11 '20 at 13:25
1

@user248921 first of all, you can store anything in string array , so you can make string array and store a line in array and use value in code whenever you want. you can use the below code to store heterogeneous(containing string, int, boolean,etc) lines in array.

public class user {
 public static void main(String x[]) throws IOException{
  BufferedReader b=new BufferedReader(new FileReader("<path to file>"));
  String[] user=new String[500];
  String line="";
  while ((line = b.readLine()) != null) {
   user[i]=line; 
   System.out.println(user[1]);
   i++;  
   }

 }
}
NikhilP
  • 1,403
  • 13
  • 22
0

This is a nice way to work with Streams and Collectors.

List<String> myList;
try(BufferedReader reader = new BufferedReader(new FileReader("yourpath"))){
    myList = reader.lines() // This will return a Stream<String>
                 .collect(Collectors.toList());
}catch(Exception e){
    e.printStackTrace();
}

When working with Streams you have also multiple methods to filter, manipulate or reduce your input.

Babofett
  • 154
  • 3
  • 10
0

For Java 11 you could use the next short approach:

  Path path = Path.of("file.txt");
  try (var reader = Files.newBufferedReader(path)) {
      String line;
      while ((line = reader.readLine()) != null) {
          System.out.println(line);
      }
  }

Or:

var path = Path.of("file.txt");
List<String> lines = Files.readAllLines(path);
lines.forEach(System.out::println);

Or:

Files.lines(Path.of("file.txt")).forEach(System.out::println);
Volodya Lombrozo
  • 1,239
  • 9
  • 20