Read the formatted .txt file into the variable : Java
I have a formatted text file called cars.txt; It is separated by tabs.
Name Length Width
truck1 18.6 8.1
suv1 17.4 7.4
coupe1 14.8 5.4
mini1 14.1 5.0
sedan1 16.4 6.1
suv2 17.5 7.3
mini2 14.3 5.2
sedan2 16.5 6.2
I
need to read this information in so I can use it later in the calculation.
That’s what I’m thinking at the moment, but I’m having a hard time piecing together what I need to execute.
public class Class{
public void readFileIn(){
Scanner sc = new Scanner(new FileReader("cars.txt");
try{
while (sc.hasNextLine()){
if (/**something that catches strings*/){
method1(string1, double1, double2);
method2(double1, double2);
}
}
}catch(FileNotFoundException exception){
System.out.println("File dosen't exist");
}
}
}
Solution
Scanner and Buffer Reader are no longer used often because Java provides a better way to achieve the same results with less code.
I can see at least three possible ways to solve your problem:
Method 1: If you can use at least Java 8, then I recommend using java.nio.file library to read the file as a stream of lines :
Stream<String> linesStream=Files.lines("cars.txt");
Then depending on what you need to do, you can use it forEach This will loop on each line of the flow:
linesStream.forEach(e -> e.myMethod());
Or Java Collectors perform the calculations you need. A good tutorial on collectors can be found here
Method 2: You can use the Apache Commons library to achieve the same goal. In particular, you can use FileUtils StringUtils
File carFile=new File("cars.txt");
LineIterator lineIterator=lineIterator(carFile);
for(String line : lineIterator) {
String[] my values=StringUtils.split(line);
do whatever you need
}
Method 3: Use Jackson to convert your file to JSON or Java objects, which you can then use for your own conversions. Here is an example that explains how to convert CSV to JSON. With a deep dive into the Jackson documentation, you can apply it to your case.