简体   繁体   English

从Java中的文本文件读取字符串

[英]Reading Strings from text files in java

im studying for my programming final exam. 我正在为我的编程期末考试而学习。 I have to write a program which opens a file which is stored in the string fileName and look in the file for a String called personName and this should print the first string after personName then the program should terminate after printing it, if the argument personName is not in the file then it should print "this name doen't exsit" then if an IOException occurs it should then print "there is an IO Error" and the program should exsit using system.exit(0) 我必须编写一个程序来打开一个存储在字符串fileName中的文件,并在文件中查找一个名为personName的字符串,这应该在personName之后打印第一个字符串,然后该程序应该在打印后终止,如果参数personName是不在文件中,则应打印“此名称不存在”,然后,如果发生IOException,则应打印“存在IO错误”,程序应使用system.exit(0)退出

the program should use the file info.txt and each line should contain two strings first string name and second age. 程序应使用文件info.txt,每行应包含两个字符串,第一个字符串名称和第二个年龄。

everything must be in one method 一切都必须合而为一

data.txt contains data.txt包含

Max 60.0 最高60.0

joe 19.0 乔19.0

ali 20.0 阿里20.0

my code for this so far is : 到目前为止,我的代码是:

public class Files{

    public void InfoReader(String fileName, String personName)
    {

      try{
         try{
                   // Open the file that is the first 
                  // command line parameter
                  FileInputStream fstream = new FileInputStream("C://rest//data.txt");
                  // Get the object of DataInputStream

                  DataInputStream in = new DataInputStream(fstream);
                  BufferedReader br = new BufferedReader(new InputStreamReader(in));

                  //Read File Line By Line
                  while ((fileName = br.readLine()) != null) {
                      // Print the content on the console
                      (new Files()).infoReader("info.txt","Joe"); //this prints the age
                  }
                  //Close the input stream
                  in.close();
              }

              catch (IOException e)
              {//Catch exception if any
                    System.out.println(" there is an IO Error");
                    System.exit(0);
              }
     }
    catch (Exception e)
              {//Catch exception if any
                    System.out.println("that name doesn't exists");

              }
    }
}

infoReader(info.txt,Joe); should print 19.0 应该打印19.0
But I am getting a java.lang.StackOverflowError 但是我收到一个java.lang.StackOverflowError

any help would be much appreciated!! 任何帮助将非常感激!!

Thanks in advance! 提前致谢!

This is what I think you are trying to do. 这就是我想您正在尝试做的。 And if doesn't, at least can work as an example. 如果没有,至少可以作为示例。 Just as amit mentions, your current error is because of the recursive call, which I think is not necessary. 就像amit提到的那样,您当前的错误是由于递归调用引起的,我认为这是不必要的。

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;

public class Files {

    public void InfoReader(String fileName, String personName) {
        try {
            // Open the file that is the first command line parameter
            FileInputStream fstream = new FileInputStream(fileName);

            // Get the object of DataInputStream
            DataInputStream in = new DataInputStream(fstream);
            BufferedReader br = new BufferedReader(new InputStreamReader(in));

            String line = null;

            //Loop until there are no more lines in the file
            while((line = br.readLine()) != null) {
                //Split the line to get 'personaName' and 'age'.
                String[] lineParts = line.split(" ");

                //Compare this line personName with the one provided
                if(lineParts[0].equals(personName)) {
                    //Print age
                    System.out.println(lineParts[1]);
                    br.close();
                    System.exit(0);
                }
            }

            br.close();
            //If we got here, it means that personName was not found in the file.
            System.out.println("that name doesn't exists");
        } catch (IOException e) {
            System.out.println(" there is an IO Error");
        }
    }
}

If you use the Scanner class, it would make your life so much easier. 如果您使用Scanner类,它将使您的生活变得更加轻松。

  Scanner fileScanner = new Scanner (new File(fileName));

  while(fileScanner.hasNextLine()
   {
      String line = fileScanner.nextLine();

      Scanner lineScanner = new Scanner(line);

      String name = lineScanner.next(); // gets the name
      double age  = Double.parseDouble(lineScanner.next()); // gets the age

      // That's all really! Now do the rest!
   }

使用commons-io,不要忘记编码!

List<String> lines = FileUtils.readLines(file, encoding)

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

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