从文本文件中读取字符串和整数输入

时间:2015-02-21 20:04:12

标签: java input

我有一个文字文件,我正在使用BufferedReader阅读。文本文件的格式为(String,String,Integer)。我使用方法inFile.readLine()读取每一行并转换为String。我想我可以使用Integer提取Integer.parse部分内容,但不要让我使用nextLine(),我认为因为这样做了Scanner而非BufferedReader

以下是我所拥有的:

 try{
  String nextLine;
  String title = "";
  String department = "";
  int year;

  BufferedReader inFile = new BufferedReader(new FileReader(inputName));

  while((nextLine = inFile.readLine())!= null){

    title = nextLine.nextLine();
    department = nextLine.nextLine();
    year = Integer.parseInt(nextLine);
    newList.addCourse(new Course(title, department, year));  
  } 

  inFile.close();
  }

有人知道我如何阅读文本文件的String部分吗?

2 个答案:

答案 0 :(得分:0)

最好将Scanner用于您的任务。但是如果Title或department有空格,你需要指定一些分隔符。

try{
    String nextLine;
    String title = "";
    String department = "";
    int year;

    BufferedReader inFile = new BufferedReader(new FileReader(inputName));
    Scanner in = new Scanner(inFile);
    while((nextLine = inFile.readLine())!= null){

        title = in.next(); //if title has spaces, you need to use next(Pattern) instead or delimiter
        department = in.next(); //if department has spaces, you need to use next(Pattern) instead or delimiter
        year = in.nextInt();
        newList.addCourse(new Course(title, department, year));
    }

    inFile.close();
} catch (FileNotFoundException e) {
    e.printStackTrace();  
} catch (IOException e) {
    e.printStackTrace(); 
}

答案 1 :(得分:0)

nextLine是一个String,String没有nextLine方法。但是,为什么要在已经为此条件分配下一行的String上调用nextLine

while((nextLine = inFile.readLine())!= null)

如果您的信息总是由3行(标题,部分和年份)组成,那么您可以这样做:

while((nextLine = inFile.readLine())!= null){

   title = nextLine;
   department = inFile.readLine();
   year = Integer.parseInt(inFile.readLine());
   newList.addCourse(new Course(title, department, year));  
} 

但是,请确保它们总是以3行为一组,否则您将遇到异常。

最好的方法是将所有3个数据放在同一行,用分隔符分隔,这样你就可以做到:

String[] info;
while((nextLine = inFile.readLine()) != null)
{
    info  = nextLine.split(";");//; would be the delimiter
    title = info[0];
    department = info[1];
    year = Integer.parseInt(info[2]);
}