如何使用Java读取文本文件的特定部分 [英] How to read specific parts of the text file using Java

查看:296
本文介绍了如何使用Java读取文本文件的特定部分的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含的文本文件

I have a text file that contains

"[PartA]
1
2
3
[PartB]
4
5
6
[PartC]
7
8
9"

到目前为止,我所做的只是阅读[PartA] 这是我的代码:

what I have done so far is to read [PartA] only here's my code:

try
    {
        BufferedReader fw = new BufferedReader(new FileReader(new File(filename)));

        while(!((content=fw.readLine()).equals("[PartB]")))
        {
            System.out.println(content);
        }
    }
    catch(Exception e)
    {

    }

那我怎么只读PartB或PartC?

so how can I read only PartB or only PartC?

推荐答案

您可以说

boolean partB = false;
content = fw.readLine();
while(content != null) {
    if(content.equals("[PartA]")) {
        partB = false;
    } else if (content.equals("[PartB]")) {
        partB = true;
    } else if (content.equals("[PartC]")) {
        partB = false;
    }
    if (partB) {
        System.out.println(content);
    }
    content = fw.readLine();
}

并对PartC遵循相同的逻辑

and follow that same logic for PartC

这篇关于如何使用Java读取文本文件的特定部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆