Reading from Text file but only store specific parts

时间:2016-04-04 18:59:27

标签: java

I am trying to store details of a Car with its x coordinate and its y coordinate from a text document. here is what the text document looks like (the '760' is on another line intentionally)

I am wondering if there is a way to read the file and just store the car name and x & y coordinates. I already have a constructor set up to take a name, x & y. I also have this Scanner set up:

File file;
            file = new File("CarInfo.txt");

            try (Scanner sc = new Scanner(file)) {
    while (sc.hasNext()) {
        String carTab = sc.next();
        // Looking for tag 'Car'
        if (!carTab.equals("Car:")) continue;

        if (!sc.hasNext()) {
            break;
        }

        String car = sc.next();
        if (!sc.hasNextInt()) {
            continue;
        }
        int x = sc.nextInt();
        if (!sc.hasNextInt()) {
            break;
        }
        int y = sc.nextInt();
        System.out.println(car + " " + x + " " + y);
    }



} catch (FileNotFoundException e) {
    System.out.println("File not found");
}

I've looked around and seen people using .next(); but I cant get it to work.

Edit:

Error Received from code (Keqiang Li):

Exception in thread "AWT-EventQueue-0" java.util.InputMismatchException
    at java.util.Scanner.throwFor(Scanner.java:864)
    at java.util.Scanner.next(Scanner.java:1485)
    at java.util.Scanner.nextDouble(Scanner.java:2413)
    at traingui.code.TrainGui$1.run(TrainGui.java:37)
    at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:311)
    at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:756)
    at java.awt.EventQueue.access$500(EventQueue.java:97)
    at java.awt.EventQueue$3.run(EventQueue.java:709)
    at java.awt.EventQueue$3.run(EventQueue.java:703)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:76)
    at java.awt.EventQueue.dispatchEvent(EventQueue.java:726)
    at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:201)
    at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:116)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:105)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:93)
    at java.awt.EventDispatchThread.run(EventDispatchThread.java:82)

4 个答案:

答案 0 :(得分:1)

{{1}}

答案 1 :(得分:0)

这将完成这项工作,考虑到您的值可以分为两行。

import java.io.*;
import java.util.Scanner;

public class StationTest {
    public static void main(String[] args) {
        File file = new File("StationInfo.txt");
        String token1 = "";
        try {
            Scanner sc = new Scanner(file);
            while (sc.hasNext()) {
                String[] acceptedValues = new String[3];
                String line = sc.nextLine();
                String[] values = line.split(" ");

                for (int i = 1; i < values.length; i++) {
                    acceptedValues[i - 1] = values[i];
                }

                if (values.length < 4) {
                    String nextLine = sc.nextLine();
                    String[] nextLineValues = nextLine.split(" ");
                    for (int i = 1; i <= acceptedValues.length + 1 - values.length; i++) {
                        acceptedValues[values.length + i - 2] = nextLineValues[i - 1];
                    }
                }
            }

            // Do as you wish with these values, setting them in your model class.
            System.out.println("Name: " + acceptedValues[0]);
            System.out.println("X: " + acceptedValues[1]);
            System.out.println("Y: " + acceptedValues[2]);

            sc.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }
}

答案 2 :(得分:0)

您可以使用正则表达式解决问题:

File file = new File("StationInfo.txt");

    String line = "";

    try {

        Scanner sc = new Scanner(file);

        while (sc.hasNextLine()) {

            String name;
            double x;
            double y;

            // find next line
            String temp = sc.nextLine();
            try {
                Double.parseDouble(temp);
                line += " " + temp;
            } catch(NumberFormatException e) {
                line = temp;
            }

            String regex = "^(\\w+:)\\s(\\w+)\\s(\\d+)\\s+(\\d+)";

            if(line.matches(regex)) {
                name = line.replaceAll(regex, "$2");
                x = Double.parseDouble(line.replaceAll(regex, "$3"));
                y = Double.parseDouble(line.replaceAll(regex, "$4"));
                System.out.println("Name = " + name + ", x = " + x + ", y = " + y);
            }

            // TrainNetwork.newStation.addStation(token1);
        }
        sc.close();



        // System.out.println(TrainNetwork.newStation);


    } catch (FileNotFoundException e) {
        e.printStackTrace();    
    }

这里正则表达式找到字符串的不同部分,并将数据存储在名为name,x和y的3个变量中。

编辑:现在代码识别是否有回车符,并且还可以使用最后一行数据。 如果你想在单词之间添加多个空格,请务必使用此String regex = "^(\\w+:)\\s+(\\w+)\\s+(\\d+)\\s+(\\d+)";

更改正则表达式

你早早改变了&#34; Station:&#34;进入&#34;地点:&#34;所以我假设你并不关心第一个单词但是如果你想接受字符串只是以#34; Station开头:&#34;只需使用String regex = "^(Station:)\\s(\\w+)\\s(\\d+)\\s+(\\d+)";

更改正则表达式

答案 3 :(得分:0)

您可以为工作站创建另一个对象,然后将每个工作站对象存储在ArrayList中,该文件位于您具有文件读取代码的文件中:

电台对象

public class Station {

    private String name;
    private ArrayList<Double> coords;

    public Station(String name, ArrayList<Double> coords){
        this.name = name;
        this.coords = coords;
    }

}

您的代码已修改

    File file = new File("StationInfo.txt");
    Scanner sc = new Scanner(file);
    ArrayList<Station> stationObj = new ArrayList<>();
    ArrayList<Double> temp = new ArrayList<>();
    String stationName = "";

    while (sc.hasNext()) {
        String token = sc.next();

        if (!token.trim().equalsIgnoreCase("Station:")) {     
            try{
                temp.add(Double.parseDouble(token));
            } catch (Exception e){
                stationName = token;
            }
        }

        // The below will work for when you have 1 coordinate or both coordinates.

        if(!stationName.equals("") && !stationName.equalsIgnoreCase("Station:") && !temp.isEmpty() && (!sc.hasNextDouble() || !sc.hasNextInt())){
            stationObj.add(new Station(stationName, temp));
            temp = new ArrayList<>();
            stationName = "";
        }

    }

如果您调试并查看stationObj Arraylist,您将看到每个电台及其坐标存储在列表中的每个电台对象中。