我正在尝试读取此文件,然后将其放入列表中:
23333
Manuel Oliveira
19
222222
Mário Santos
18
使用扫描仪。 如果忽略 19 和 222222 之间的空行,这就是我所做的。
public List<Aluno> lerFicheiro ( String nomeF) throws FileNotFoundException{
List<Aluno> pauta = new LinkedList<Aluno>();
try{
Scanner s = new Scanner ( new File ( nomeF));
int cont = 0;
String numero = null;
String nome = null;;
String nota;
while ( s.hasNextLine())
{
if ( cont ==0)
{
numero = s.nextLine();
}
else
{
if ( cont == 1)
nome = s.nextLine();
else
{
if ( cont == 2)
{
nota = s.nextLine();
cont =-1;
pauta.add( new Aluno(Integer.valueOf(numero), nome, nota));
}
}
}
cont++;
}
s.close();
}
catch ( FileNotFoundException e)
{
System.out.println(e.getMessage());
}
return pauta;
}
但我不知道如何用空行来阅读它。 谢谢。
最佳答案
对于初学者来说,你已经有了一个基本状态机的良好开端。您可以通过两种方式来考虑空行:
- 您对任何空行都不感兴趣。因此,您只需忽略它们,并且不要更改您的
cont
。 - 您对“nota”后面的空行特别不感兴趣。在这种情况下,您应该将其添加为第四种状态。
第一种方法的优点是,即使文件中存在多个空行,或者名称后面有一个空行,也会被忽略。如果“nota”后面没有的其他空行有用,那么第二种方法会更好。
我认为阅读该行,然后根据cont
决定如何处理它会更优雅。因此,对于第一种方法(忽略任何空行):
while ( s.hasNextLine()){
// First read
String theLine = s.nextLine();
// Ignore it if it's empty. That is, only do something if
// the line is not empty
if ( ! theLine.isEmpty() ) {
if ( cont == 0){
numero = theLine; // You use the line you have read
}else if ( cont == 1) {
nome = theLine;
}else {
nota = theLine;
cont =-1;
pauta.add( new Aluno(Integer.valueOf(numero), nome, nota));
}
cont++;
}
}
当您读取空行时,状态 (cont
) 不会更改。所以就好像这条线从未存在过。
请注意,最好使用常量,而不仅仅是 0
、1
、2
,这样它们才有意义。
还要注意正确编写if...else if...else
的方法。您不需要始终将它们放在大括号中。
关于java - 如何在读取文件时跳过空行(java)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30983959/