【问题标题】:Read file until certain character (BufferedReader) [closed]读取文件直到某个字符(BufferedReader)[关闭]
【发布时间】:2014-07-30 04:28:51
【问题描述】:

这是我的代码不起作用:

try 
{
    while ((line1 = br.readLine()).substring(6).equals(name)) 
    {
        text = text + line1; 
        //text = text + '\n';
    }
} 
catch (IOException e) 
{
    // TODO Auto-generated catch block
    e.printStackTrace();
}

我要做的是从文本文件中读取文本:

Name: Thailand.jpg.
Brief: This is Pattaya
Info: Nice city you know

Name: Austria.jpg
Brief: This is Austria
Info: Schwarzenegger was born here

现在我只想设置“这是奥地利”文本。但不能。

谢谢!

【问题讨论】:

  • 所以您只想从文件中获取字符串“This is Austria”?
  • 这一行while ((line1 = br.readLine()).substring(6).equals(name)) { 是一团糟。分成可读的逻辑。还有什么是name?为什么substring(6)
  • 名字是奥地利。我需要来自奥地利的文本。
  • 那么你的问题是什么?注意,您需要先测试readLine() 的结果是否为空,然后再对其进行任何其他操作。此代码将在文件末尾抛出NullPointerException

标签: java bufferedreader


【解决方案1】:

首先,我不确定你要在这里做什么。 @Rod_Algonquin 也问了这个问题。you only want to get the string "This is Austria" from the file?,但你没有对此发表任何评论。

假设你要做类似的事情,你可以尝试如下。

           try {
            BufferedReader br=new BufferedReader(
                          new FileReader(new File("/home/ruchira/Test.txt")));
            String line;
            String text = "";
            try {
                while ((line=br.readLine())!=null){
                       if(line.contains("Austria.jpg")){
                           String line1=br.readLine();
                           if(line1!=null){
                               text=text+line1.split(": ")[1];
                           }
                       }
                }
                System.out.println(text);
            } catch (IOException e) {
                e.printStackTrace();
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }

【讨论】:

  • 这就是我想要的。谢谢!!!
  • @NurgulAlshyn 不客气
【解决方案2】:

您的子字符串索引错误。请重新计算。此外,您将必须检查空指针条件。您应该将 while 循环条件更改为:

try 
{    
    while((line1=br.readLine())!=null && line1.substring(8).equals(name))
    {
        text = text + line1; 
        //text = text + '\n';
    }
}
catch (FileNotFoundException e) 
{
    e.printStackTrace();
} 
catch (IOException e) 
{
    e.printStackTrace();
}

在计算索引时,您还应该考虑空格。因此,您所需的子字符串索引变为 8 而不是 6。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-04-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-08
    相关资源
    最近更新 更多