簡體   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