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.
-
1Please be more specific in your question, what exactly do you wanna do with each line ? – Valentin Rocher Jan 12 '10 at 14:03
-
This question should help you: http://stackoverflow.com/questions/224952 – Fabian Steeg Jan 12 '10 at 14:05
-
@Fabian Steeg: The question you linked to doesn't address dealing with different data types like this one does. – Powerlord Jan 12 '10 at 14:16
-
@Bemrose, I'm not exactly sure what the author of the question means, but I understand it as *where every line can contain different kinds and amounts of numbers*. But yeah, I don't know. – Fabian Steeg Jan 12 '10 at 14:27
10 Answers
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.

- 321,842
- 108
- 597
- 820
-
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
-
'No-one knows about it' is sheer nonsense, as is 'can do almost anything with text'. Don't make pointless and extravagant claims. – user207421 May 08 '23 at 08:25
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."

- 250
- 1
- 2
- 7
-
This method appears to now be deprecated. Specifying a charset is preferred. – payne Apr 06 '22 at 21:25
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.

- 14,397
- 15
- 77
- 118
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();
}

- 11,667
- 45
- 59
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 );
}

- 39,603
- 20
- 94
- 123

- 39
- 2
-
@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
@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++;
}
}
}

- 1,508
- 14
- 23
-
You cannot 'store anything in a String array'. You can only store Strings. – user207421 May 08 '23 at 08:26
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class PredmetTest {
public static void main(String[] args) {
// Define the file path to read the subject names and grades from
String filePath = "path_to_your_file.txt";
// Create a list to store the subjects
List<Predmet> predmeti = new ArrayList<>();
// Read the file and populate the predmeti list
try (BufferedReader br = new BufferedReader(new FileReader(filePath))) {
String line;
while ((line = br.readLine()) != null) {
String[] parts = line.split(" ");
String subjectName = parts[0];
// Parse the grades for the subject
List<Integer> grades = new ArrayList<>();
for (int i = 1; i < parts.length; i++) {
grades.add(Integer.parseInt(parts[i]));
}
// Create a new Predmet object with the subject name and grades
Predmet predmet = new Predmet(subjectName, grades);
// Add the Predmet object to the list
predmeti.add(predmet);
}
} catch (IOException e) {
e.printStackTrace();
}
// Calculate and display the average grade for each subject
double highestAverage = -1;
Predmet predmetWithHighestAverage = null;
for (Predmet predmet : predmeti) {
// Calculate the average grade for the subject
double average = predmet.calculateAverage();
// Update the subject with the highest average if necessary
if (average > highestAverage) {
highestAverage = average;
predmetWithHighestAverage = predmet;
}
// Display the subject and its average grade
System.out.println("Subject: " + predmet.getSubjectName());
System.out.println("Average grade: " + average);
System.out.println();
}
// Display the subject with the highest average grade
if (predmetWithHighestAverage != null) {
System.out.println("Subject with the highest average grade: " + predmetWithHighestAverage.getSubjectName());
}
}
}
public class Predmet {
private String subjectName;
private List<Integer> grades;
public Predmet(String subjectName, List<Integer> grades) {
this.subjectName = subjectName;
this.grades = grades;
}
public String getSubjectName() {
return subjectName;
}
public List<Integer> getGrades() {
return grades;
}
public double calculateAverage() {
int sum = 0;
for (int grade : grades) {
sum += grade;
}
return (double) sum / grades.size();
}
}

- 1
-
1Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community May 08 '23 at 09:39
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Predmet {
String naziv;
float ocjena;
public Predmet(String naziv, float ocjena) {
this.naziv = naziv;
this.ocjena = ocjena;
}
}
public class PredmetTest {
public static void main(String[] args) {
List<Predmet> predmeti = new ArrayList<>();
// Učitavanje predmeta iz datoteke
try {
File file = new File("predmeti.txt");
Scanner scanner = new Scanner(file);
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
String[] parts = line.split(" ");
String naziv = parts[0];
float ocjena = Float.parseFloat(parts[1]);
Predmet predmet = new Predmet(naziv, ocjena);
predmeti.add(predmet);
}
scanner.close();
} catch (FileNotFoundException e) {
System.out.println("Datoteka nije pronađena.");
e.printStackTrace();
}
// Ispisivanje predmeta i zaključne ocjene
float najveciProsjek = 0;
Predmet predmetSaNajvecimProsjekom = null;
for (Predmet predmet : predmeti) {
System.out.println("Predmet: " + predmet.naziv);
System.out.println("Zaključna ocjena: " + predmet.ocjena);
System.out.println();
if (predmet.ocjena > najveciProsjek) {
najveciProsjek = predmet.ocjena;
predmetSaNajvecimProsjekom = predmet;
}
}
// Ispisivanje predmeta s najvišim prosjekom
if (predmetSaNajvecimProsjekom != null) {
System.out.println("Predmet s najvišim prosjekom: " + predmetSaNajvecimProsjekom.naziv);
System.out.println("Prosjek ocjena: " + predmetSaNajvecimProsjekom.ocjena);
}
}
}

- 1
-
1Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community May 08 '23 at 09:39
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.

- 182
- 3
- 11
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);

- 2,325
- 2
- 16
- 34