Reputation:
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.
Upvotes: 2
Views: 46332
Reputation: 1703
@user248921 first of all, you can store any text 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++;
}
}
}
Upvotes: 0
Reputation: 1
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);
}
}
}
Upvotes: 0
Reputation: 1
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();
}
}
Upvotes: 0
Reputation: 3476
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);
Upvotes: -1
Reputation: 15423
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.
Upvotes: 3
Reputation: 192
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.
Upvotes: -1
Reputation: 39
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 );
}
Upvotes: 1
Reputation: 250
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."
Upvotes: 9
Reputation: 328770
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.
Upvotes: 12
Reputation: 11669
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();
}
Upvotes: 2