查找文本文件的特定行(而不是line_number)并将其存储为新的String

时间:2011-08-13 16:15:24

标签: java arrays text-files

我正在尝试使用FileReader和BufferedReader类在java中读取文本文件。在一个在线教程之后,我创建了两个类,一个名为ReadFile,一个名为FileData。 然后我尝试提取文本文件的一小部分(即行“ENTITIES”和“ENDSEC”之间)。最后我想告诉程序找到上面提到的特定行并将其存储为Xvalue,稍后我可以使用它。 我真的在努力弄清楚如何做最后一部分......任何帮助都会非常适合!

// FileData Class

    package textfiles;

    import java.io.IOException; 


    public class FileData {

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

    String file_name = "C:/Point.txt";

    try {

        ReadFile file = new ReadFile (file_name);
        String[] aryLines = file.OpenFile();

        int i;
        for ( i=0; i < aryLines.length; i++ ) {
        System.out.println( aryLines[ i ] ) ;
}

    }

    catch (IOException e) {
        System.out.println(e.getMessage() );
    }

 }

 }

// ReadFile Class

    package textfiles;

    import java.io.IOException;
    import java.io.FileReader;
    import java.io.BufferedReader;
    import java.lang.String;

    public class ReadFile {

private String path;

public ReadFile (String file_path) {
    path = file_path;
}

public String[] OpenFile() throws IOException {

    FileReader fr = new FileReader (path);
    BufferedReader textReader = new BufferedReader (fr); 

     int numberOfLines = readLines();
      String[] textData = new String[numberOfLines];
     String nextline = "";

     int i;
             // String Xvalue; 

    for (i=0; i < numberOfLines; i++) {
         String oneline = textReader.readLine();

         int j = 0;

         if (oneline.equals("ENTITIES")) {
             nextline = oneline;
             System.out.println(oneline);
             while (!nextline.equals("ENDSEC")) {
                 nextline = textReader.readLine();
                 textData[j] = nextline;

            //  xvalue = ..........

                 j = j + 1;
                 i = i+1;
             }
         }       
         //textData[i] = textReader.readLine();
     }

     textReader.close( );
     return textData;

}

int readLines() throws IOException {

    FileReader file_to_read = new FileReader (path);
    BufferedReader bf = new BufferedReader (file_to_read);

    String aLine;
    int numberOfLines = 0;

    while (( aLine = bf.readLine()) != null ) {
        numberOfLines ++;
    }

    bf.close ();

    return numberOfLines;

}

}

2 个答案:

答案 0 :(得分:1)

我不知道您要专门寻找哪一行,但是您可能需要使用一些方法来执行此类操作:

private static String START_LINE = "ENTITIES";
private static String END_LINE = "ENDSEC";

public static List<String> getSpecificLines(Srting filename) throws IOException{
    List<String> specificLines = new LinkedList<String>();
    Scanner sc = null;
    try {
        boolean foundStartLine = false;
        boolean foundEndLine = false;
        sc = new Scanner(new BufferedReader(new FileReader(filename)));
        while (!foundEndLine && sc.hasNext()) {
            String line = sc.nextLine();
            foundStartLine = foundStartLine || line.equals(START_LINE);
            foundEndLine = foundEndLine || line.equals(END_LINE);
            if(foundStartLine && !foundEndLine){
                specificLines.add(line);
            }
        }
    } finally {
        if (sc != null) {
            sc.close();
        }
    }
    return specificLines;
}

public static String getSpecificLine(List<String> specificLines){
    for(String line : specificLines){
        if(isSpecific(line)){
            return line;
        }
    }
    return null;
}

public static boolean isSpecific(String line){
    // What makes the String special??
}

答案 1 :(得分:0)

当我做对了你想要存储 ENTITIES ENDSEC 之间的每一行?

如果是,您可以简单地定义 StringBuffer ,并将这些中的所有内容附加到关键字。

// This could you would put outside the while loop
StringBuffer xValues = new StringBuffer();

// This would be in the while loop and you append all the lines in the buffer
xValues.append(nextline);

如果您想在这些关键字之间存储更多特定数据,那么您可能需要使用正则表达式并获取所需的数据并将其放入设计的DataStructure中(A class you由我们自己定义。

顺便说一下。我认为您可以使用以下代码更轻松地阅读文件:

BufferedReader reader = new BufferedReader(new
InputStreamReader(this.getClass().getResourceAsStream(filename)));

try {
   while ((line = reader.readLine()) != null) {
     if(line.equals("ENTITIES") {
       ...
     }

} (IOException e) {
   System.out.println("IO Exception. Couldn't Read the file!");
}

然后你不必先读取文件有多少行。你只是开始阅读直到结束:)。

修改

我仍然不知道我是否明白这一点。因此,如果 ENTITIES POINT 10 1333.888 20 333.5555 ENDSEC 是一行,那么您可以使用拆分(“”)方法。

让我用一个例子来解释:

String line = "";
String[] parts = line.split(" ");
float xValue = parts[2]; // would store 10
float yValue = parts[3]; // would store 1333.888
float zValue = parts[4]; // would store 20
float ...    = parts[5]; // would store 333.5555

<强> EDIT2:

或者是另一条线上的每个点(x,y,..)?!

所以文件内容是这样的:

ENTITIES POINT 
10 
1333.888 // <-- you want this one as xValue 
20 
333.5555 // <-- and this one as yvalue?
ENDSEC

BufferedReader reader = new BufferedReader(new
InputStreamReader(this.getClass().getResourceAsStream(filename)));

try {
   while ((line = reader.readLine()) != null) {
     if(line.equals("ENTITIES") {

        // read next line
        line = reader.readLine();
        if(line.equals("10") {
         // read next line to get the value
         line = reader.readLine(); // read next line to get the value
         float xValue = Float.parseFloat(line);
        }

        line = reader.readLine();

        if(line.equals("20") {
           // read next line to get the value
           line = reader.readLine(); 
           float yValue = Float.parseFloaT(line);
        }
     }

} (IOException e) {
   System.out.println("IO Exception. Couldn't Read the file!");
}

如果文件中有多个ENTITIES,则需要创建一个存储xValue,yValue的类,或者您可以使用 Point 类。然后你将创建这些点的ArrayList并只是追加它们。