简体   繁体   English

如何从JAVA中的文件中读取这些数据

[英]How to read these data from a file in JAVA

I have this format of data 我有这种格式的数据

n
l
p1(x1) p1(x2) imp(p1)
p2(x1) p2(x2) imp(p2)
: : :
pl(x1) pl(x2) imp(pl)
r
q1(x1) q1(x2) imp(q1)
q2(x1) q2(x2) imp(q2)
: : :
qr(x1) qr(x2) imp(qr)

where n, l(number of p's) , and r(number of q's) are integers. 其中n,l(p的数量)和r(q的数量)是整数。 I know how to read only integers from a file but how I can read the lines that includes strings and get the values of x1, x2, and p1 for each line?! 我知道如何从文件中只读取整数,但是如何读取包含字符串的行并获取每行的x1,x2和p1的值?! Thanks in Advance. 提前致谢。

Here is my code for reading integers only. 这是我的读取整数的代码。

try {
            reader = new BufferedReader(new FileReader(file));
            String text = null;
            while ((text = reader.readLine()) != null) {
                // The first line gives the number of nodes (You will use to create the int[][] graph = new int[nOfNodes][nOfNodes];)
                if (c == 0) {
                    numberOfNodes = Integer.parseInt(text.trim());
                } // The second one gives the number of edges
                else if (c == 1) {
                    nOfEdges = Integer.parseInt(text.trim());
                    graph2 = new double[nOfEdges][3];
                } // And third the list of special nodes
                // `nodes` will now contains only your special constrained one
                else if (c == 2) {
                    String[] str = text.split(" ");
                    for (int i = 0; i < str.length; i++) {
                        if (str[i].trim().length() > 0) {
                            nodes.add(Integer.parseInt(str[i]));
                        }
                    }
                } else { // Then you have your edges descriptors
                    String[] str = text.split(" ");
                    for (int i = 0; i < str.length; i++) {
                        if (str[i].trim().length() > 0) {
                            graph2[c - 4][i] = Double.parseDouble(str[i]);
                        }
                    }
                }
                c++;
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (reader != null) {
                    reader.close();
                }
            } catch (IOException e) {
                System.out.print(e);
            }
        }

A quick google search led me to this tutorial on basic java I/O , and in particular, there is a section on Scanning that demonstrates how to conveniently break (aka "split" or "tokenize") your input into smaller pieces and possibly parse them in a more structured manner. 一个快速的谷歌搜索引导我学习基本的Java I / O教程 ,特别是,有一个关于扫描部分演示如何方便地将您的输入分解(也称为“分割”或“标记化”)为较小的片段并可能解析他们以更有条理的方式。

The documentation for the Scanner class has more detailed examples. Scanner类文档有更详细的示例。 I think you need something like: 我想你需要这样的东西:

String input = "p1(x1) p1(x2) imp(p1)";
Scanner s = new Scanner(input);
s.findInLine("(\\w+)\\((\\w+)\\) (\\w+)\\((\\w+)\\) imp\\((\\w+)\\)");

I haven't tested this yet, but basically "\\\\(" is for parsing a "(" and "\\\\w+" is for parsing any sequence of one or more characters. If you want to parse a sequence of digits then use "\\\\d+" instead. 我还没有测试过,但基本上“\\\\(”用于解析“(”和“\\\\ w +”用于解析一个或多个字符的任何序列。如果要解析一系列数字,则使用“\\\\ d +”而不是。

Hope this helps, good luck! 希望这有帮助,祝你好运!

In my opinion, the best thing for you here is using the Properties class. 在我看来,对你来说最好的事情是使用Properties类。 With the properties class you can set some properties and then read them again! 使用属性类,您可以设置一些属性,然后再次阅读它们! This is the link which I found explains it the best! 这是我发现最好解释的链接!

https://www.mkyong.com/java/java-properties-file-examples/ https://www.mkyong.com/java/java-properties-file-examples/

If you don't want that, you can simply split the line to 3 strings each one containing one piece of data. 如果您不想这样,您可以简单地将该行拆分为3个字符串,每个字符串包含一个数据。

String data[] = line.split(" ");

Now find the open bracket and the close bracket and get what is between them. 现在找到开括号和近括号,得到它们之间的内容。 I added + 1 and - 1 so that it doesn't read the braces as well, only the number between. 我添加了+ 1和-1,因此它也不会读取大括号,只读取之间的数字。

int begin = string.indexOf('(');
int end = string.indexOf(')');
string.substring(begin + 1, end - 1);

Now just parse your string into an integer. 现在只需将您的字符串解析为整数。

int number = Integer.parseInt(thedatathatyouhave);

Using matcher class like this 像这样使用matcher类

public static int numberOfPoints = -1, p=-1, q=-1;

    public static void main(String[] args) throws FileNotFoundException {

        ArrayList<Integer> dots = new ArrayList<>();
        int c = 0;
        File file = new File("D:\\ALGORTHIMS\\MASTER LEVEL\\dr. khaled\\assignment 3\\a.txt");
        BufferedReader reader = null;


        try {
            reader = new BufferedReader(new FileReader(file));
            String text = null;
            while ((text = reader.readLine()) != null) {

                try {
                    if(c==0)
                    { numberOfPoints=Integer.parseInt(text); c=1;}
                    if(c==1)
                    { p=Integer.parseInt(text);c=2;}
                    if(c==2)
                        q=Integer.parseInt(text);

                } catch (NumberFormatException e) {

                    Matcher m = Pattern.compile("\\(([^)]+)\\)").matcher(text);
        while (m.find()) {

           dots.add(Integer.parseInt(m.group(1)));
        }

                }

            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (reader != null) {
                    reader.close();
                }
            } catch (IOException e) {
                System.out.print(e);
            }
        }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM