我是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行都有一个新条目。例如,Salary是类别,3,400是金额,21/12/2015是日期。我想要做的只是阅读金额(例如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.
答案 0 :(得分:2)
跳过其他行: - )
while(opnEsoda.hasNext()) {
// skip category
opnEsoda.nextLine();
System.out.print("Amount: " + opnEsoda.nextLine()+", ");
// skip date
opnEsoda.nextLine();
System.out.println();
}
答案 1 :(得分:2)
您可以使用以下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;
}
答案 2 :(得分:2)
在我看来,这比仅仅跳过线条更清晰,它允许您在以后需要时访问跳过的元素:)
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)