-1

I'm trying to figure out a way to print out specific Strings from a .txt file.

Here is my method:

public static void writeBirdtype() {

In innSkjerm = new In(); // Reading from terminal
In fil = new In("fugler.txt"); // Reading from file   

System.out.println("Write out all the observations of a birdtype: ");
String ord = innSkjerm.readLine();

System.out.println("All the observations you asked for:");
while (fil.hasNext()) {
String linje = fil.inWord();
System.out.println(linje);

} // end of while-statement              

} // end of writeBirdType() method

The problem is this code prints out all the Strings from a .txt file, which is not what i'm trying to accomplish. Can anyone see what I am missing here? Thank you.

4

1 回答 1

0

这是如何从文件中读取某些内容(在本例中为字符串)的示例

private String readFileAsString(String filePath) throws IOException {
    StringBuffer fileData = new StringBuffer();
    BufferedReader reader = new BufferedReader(
       new FileReader(filePath));
       char[] buf = new char[1024];
       int numRead=0;

        while((numRead=reader.read(buf)) != -1){
            String readData = String.valueOf(buf, 0, numRead);
            fileData.append(readData);
        }
        reader.close();
        return fileData.toString();
   }
   //rest implementation

编辑:这个解决方案对你来说会更好,因为它会更容易理解

您可以修改它以阅读您想要的任何内容。你现在应该这样做。

于 2013-09-17T19:01:08.300 回答