繁体   English   中英

读取Java中文本文件的特定行

[英]Reading specific lines of a text file in Java

我是Java新手。 我正在尝试在文本文件上建立数据库(不要问我为什么)。 我要做的是读取文本文件的特定行。

文本文件:

Salary
3,400
21/12/2015
Tax Refund
3
22/12/2015
Tax Refund
320
23/12/2015
Savings Deposit
1,230
23/12/2015
Bonus
343
23/12/2015

每3行有一个新条目。 例如,薪金是类别,金额是3,400,日期是2015年12月21日。 我想做的是仅读取金额(例如3,400 3 320 1,230等)。 我唯一要做的就是使用以下代码通过在真正的print语句上匹配它们来打印行:

while(opnEsoda.hasNext()) { // diabazei kathe seira sto txt
    // diabazei kathe seira kai emfanizei to value tis kathe mias ana 3.
    System.out.print("You got money from: " + opnEsoda.nextLine()+ ", "); 

    System.out.print("Amount: " + opnEsoda.nextLine()+", ");
    System.out.print("Date: " + opnEsoda.nextLine()+". ");               
    System.out.println(); 
} 

opnEsoda是扫描仪,并打印:

You got money from: Salary, Amount: 3,400, Date: 21/12/2015. 
You got money from: Tax Refund, Amount: 3, Date: 22/12/2015. 
You got money from: Tax Refund, Amount: 320, Date: 23/12/2015. 
You got money from: Savings Deposit, Amount: 1,230, Date: 23/12/2015. 
You got money from: Bonus, Amount: 343, Date: 23/12/2015.

只需跳过其他行:-)

while(opnEsoda.hasNext()) {
    // skip category
    opnEsoda.nextLine(); 

    System.out.print("Amount: " + opnEsoda.nextLine()+", ");

    // skip date
    opnEsoda.nextLine();

    System.out.println(); 
} 

您可以使用下面的JAVA8代码并以String列表格式获取文件。 检索列表的行号“ n”将很容易。

        int n=2;
        List<String> fileLines = Files.readAllLines(Paths.get("c:\\abc.txt"));
        while(n<fileLines.size()){
            fileLines.get(n);
            n+=3;
        }

我认为这比仅跳过行要干净一些,它允许您访问跳过的元素,以防日后需要它们时使用:)

do
{
    String[] entry = new String[3];

    for (int i = 0; i < 3; i++)
    {
        if (opnEsoda.hasNextLine())
        {
            // Trim removes leading or trailing whitespace.
            entry[i] = opnEsoda.nextLine().trim(); 
        }
    }

    System.out.println(entry[2]);
}
while (opnEsoda.hasNextLine)

暂无
暂无

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

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