Reading a text file in java

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

I am a complete noob in Java, so sorry if this question is a little stupid.

thanks

+5
source share
6 answers

Try a Scannerclass that 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 must really specify the encoding, otherwise you will get strange results when you encounter umlauts, Unicode, etc.

+11
source

- Apache Commons IO JAR org.apache.commons.io.FileUtils. , :

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

.

" ".

+6

, "" :

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();
}
+2

:

    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 );
    }
+1

@ user248921 First of all, you can store something in a string array, so you can create a string array and store the string in the array and use the value in the code whenever you want. you can use the code below to store heterogeneous (containing strings, int, boolean, etc.) strings in an 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++;  
   }

 }
}
0
source

This is a good 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 threads, you also have several methods for filtering, manipulating, or reducing your input.

0
source

All Articles