Randy G.
Randy G.

Reputation: 111

Reading Formatted .txt File into Variables: Java

I Have a formatted text file called cars.txt; It's 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 in this information so it can be used for calculations later on. This is my current idea but I am 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");
            }

    }
}

Upvotes: 3

Views: 156

Answers (3)

AR1
AR1

Reputation: 5023

Scanner and Buffer Reader are not used very often anymore as Java provides a better way to achieve tha same result with less code. I can see at least three possible approaches to solve your problem:

approach 1: if you can use at least Java 8, then I would suggest to use the java.nio.file libraries 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 could use either forEach that will loop on each line of the stream:

linesStream.forEach(e -> e.myMethod());

Or Java Collectors to execute the calculation that you need to. A good tutorial about Collectors can be found here. You can use collectors also to separate your string etc...

approach 2: you can use Apache Commons libraries to achieve the same goal. In particular you could use FileUtils and StringUtils. For instance:

File carFile=new File("cars.txt");

LineIterator lineIterator=lineIterator(carFile);

for(String line : lineIterator) {

         String[] my values=StringUtils.split(line);

//do whatever you need

} 

approach 3: use Jackson to transform your file into a json or a java object that you can then use for your own transformations. Here is an example explaining how to convert a CSV to JSON. With a bit of digging in the Jackson documentation, you could apply it to your case.

Upvotes: 2

Glains
Glains

Reputation: 2873

First of all, i recommend you create an Entry class that represents your data.

private class Entry {
    private String name;
    private double length;
    private double width;

    // getters and setters omitted

    @Override
    public String toString() {
        // omitted
    }
}

Next, create a method that takes a String as an arguments and is responsible for parsing a line of text to an instance of Entry. The regex \\s+ matches any whitespace characters and will split your line to its individual columns. Remember that in production, Double.valueOf can throw an RuntimeException if your are not passing a valid String.

Finally, you can read the file, here using the Java 8 stream API. Skip the first line since it includes the column header and not actual data.

private void readFile() throws Exception {
    Path path = Paths.get(/* path to your file */);

    Files.readAllLines(path).stream().skip(1).map(FileReadTest::toEntry)
            .forEach(this::action);
}

In my example, i am just printing each entry to the console:

private void action(Entry entry) {
    System.out.println(entry);
}

Resulting output:

Entry[name='truck1', length=18.6, width=8.1]
Entry[name='suv1', length=17.4, width=7.4]
Entry[name='coupe1', length=14.8, width=5.4]
Entry[name='mini1', length=14.1, width=5.0]
Entry[name='sedan1', length=16.4, width=6.1]
Entry[name='suv2', length=17.5, width=7.3]
Entry[name='mini2', length=14.3, width=5.2]
Entry[name='sedan2', length=16.5, width=6.2]

Upvotes: 1

Dreamspace President
Dreamspace President

Reputation: 1118

Here's an example of how to properly read a text file - replace the charset with the one you need.

try (final BufferedReader br = Files.newBufferedReader(file.toPath(), StandardCharsets.UTF_8)) {
    String line;
    while ((line = br.readLine()) != null) {
        System.out.println(line);
    }
} catch (IOException e) {
    e.printStackTrace();
}

Once you have the individual lines, you can split them by whitespace: str.split("\\s+");

You get an array with three entries. I guess you can figure out the rest.

Upvotes: 0

Related Questions