2
Good evening, I have been learning Java for a while and wanted to know how I could read a text file that has one or two numbers in a maximum of 10 lines. Something like the files below:
16x9_resolutions.dat
640 360
1280 720
1366 768
1600 900
1920 1080
dat ranking.
10000
9000
8900
8878
8803
7995
7967
7960
7906
7845
I managed to do that:
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
public class Files{
private String vet[] = new String[10];
public void read(String path) throws IOException {
BufferedReader buffRead = new BufferedReader(new FileReader(path));
String line = "";
int i = 0;
while (true) {
line = buffRead.readLine();
if (line != null) {
this.vet[i] = line;
i++;
} else{
break;
}
if(i == 10){
break;
}
}
buffRead.close();
}
public int getResolutions(int pos){
return Integer.parseInt(this.vet[pos]);
}
}
In the above class I can read only one number per line. I want the read() method to be able to read the two types of files I showed, in the case of two numbers per line it should put the second number in the next vector position and jump to the next line.
I saw some posts on the internet talking about split() but none showed how to use it within a loop. I wanted something like:
while (true) {
line = buffRead.readLine();
if (line != null) {
if(line.split() == "2 numeros separados por espaço"){
this.vet[i] = line.split("primeiro numero");
i++;
this.vet[i] = line.split("segundo numero");
i++;
}else{
this.vet[i] = line;
i++;
}
}else{
break;
}
if(i == 10){
break;
}
}
Thank you @hkotsubo. To make it clearer what I want to do is read values that can be int or String and that can be in pairs or alone on each line. They don’t necessarily need to be 10 but that’s the maximum amount. Your answer will already help me a lot.
– kiss_cpp
One thing I didn’t understand was the for (String part : parts), which means this : ?
– kiss_cpp
@kiss_cpp This is the Enhanced for, is just another way to go through an array. You could do
for (int i = 0; i < partes.length; i++) { String parte = partes[i]; etc...}
, which would be just the same (but when I just want to go through the array elements, no matter what the index, I usually use the Enhanced for, I find it more succinct and direct).– hkotsubo