Java 从文本文件读取,但仅存储特定部分

Java 从文本文件读取,但仅存储特定部分,java,Java,我试图从文本文档中存储具有x坐标和y坐标的汽车的详细信息。以下是文本文档的外观(“760”位于另一行) 我想知道是否有一种方法可以读取文件并只存储汽车名称和x&y坐标。我已经设置了一个构造函数来取一个名称x&y。我还设置了此扫描仪: File file; file = new File("CarInfo.txt"); try (Scanner sc = new Scanner(file)) { while (sc.hasNext()) {

我试图从文本文档中存储具有x坐标和y坐标的汽车的详细信息。以下是文本文档的外观(“760”位于另一行)

我想知道是否有一种方法可以读取文件并只存储汽车名称和x&y坐标。我已经设置了一个构造函数来取一个名称x&y。我还设置了此扫描仪:

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");
}
我环顾四周,看到人们在使用
.next()
编辑:

收到来自代码的错误(李克强):


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

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();
        }
    }
}
import java.io.*;
导入java.util.Scanner;
公共类站测试{
公共静态void main(字符串[]args){
File File=新文件(“StationInfo.txt”);
字符串标记1=“”;
试一试{
扫描仪sc=新扫描仪(文件);
while(sc.hasNext()){
String[]acceptedValues=新字符串[3];
字符串行=sc.nextLine();
字符串[]值=行。拆分(“”);
对于(int i=1;i对于(int i=1;i,可以使用正则表达式解决问题:

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+)”;


您很早就将“Station:”更改为“Place:”,因此我假设您不关心第一个单词,但如果您只想接受以“Station:”开头的字符串,只需使用
string regex=“^(Station:)\\s(\\w+)\\s(\\d+)\\s+(\\d+)”更改正则表达式即可;

您可以为桩号创建另一个对象,然后将每个桩号对象存储在一个ArrayList中,该ArrayList与读取代码的文件位于同一个文件中:

站点对象

public class Station {

    private String name;
    private ArrayList<Double> coords;

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

}
公共类电台{
私有字符串名称;
私人ArrayList coords;
公共电台(字符串名称,ArrayList坐标){
this.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 = "";
        }

    }
File File=new文件(“StationInfo.txt”);
扫描仪sc=新扫描仪(文件);
ArrayList stationObj=新的ArrayList();
ArrayList temp=新的ArrayList();
字符串stationName=“”;
while(sc.hasNext()){
字符串标记=sc.next();
如果(!token.trim().equalsIgnoreCase(“站:){
试一试{
临时添加(Double.parseDouble(令牌));
}捕获(例外e){
stationName=令牌;
}
}
//当您有一个坐标或两个坐标时,以下选项适用。
如果(!stationName.equals(“”&!stationName.equalsIgnoreCase(“站:”)&&!temp.isEmpty()&(!sc.hasNextDouble()| |!sc.hasNextInt())){
stationObj.add(新站点(站点名称、临时));
temp=新的ArrayList();
stationName=“”;
}
}

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

既然“120”故意位于另一行上”,这是“错误”吗是否可以更正?该文件是否存在任何其他异常?您可以将该文件视为一个流,其中换行符不重要(视为任何其他空白),并解析一系列4个“字段”-修复了
站点:
,空格,站点名称空格,x,空格,yI已从该代码收到此错误,但看不出是什么导致了此错误?(包含在上述代码中的错误)@Safa这是我在回答中提到的一个错误,因为您的文件可能格式不正确。因此,如果预期会出现双精度,但文件中会出现其他内容,则需要处理。这当然会引发不匹配的异常。文件中格式不正确的可能性越大,您需要在此处添加更多代码来处理它们。我是否将此添加到catch s中Section then?@Safa请查看更新。基本上,每次扫描之前,您都需要确保它的类型正确。如果不是,请跳过它并尝试查找下一站。我明白了,谢谢。很抱歉,现在没有错误,但没有打印到输出!我对
TrainNetwork.newStation.addStation()发表了评论因为我没有代码,也不知道如何使用它。
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 = "";
        }

    }