1

我有一个文本文件,其中每条奇数行都包含一个整数(当然是字符串,因为它在文本文件中),偶数行有一个时间。我只想读取数字,因此是文本文件中的奇数行。我怎么做?

import java.io.*; 

public class File { 

BufferedReader in; 
String read; 
int linenum =12;


public File(){ 
try { 
in = new BufferedReader(new FileReader("MAP_allData.txt")); 

for (linenum=0; linenum<20; linenum++){

read = in.readLine();
if(read==null){} 
else{
System.out.println(read);  }
}
in.close(); 
}catch(IOException e){ System.out.println("There was a problem:" + e); 

} 
} 

public static void main(String[] args){ 
File File = new File(); 
} 
}

截至目前,它将读取所有(奇数和偶数)行,直到不再从(null)读取

因为我的偶数行是一个时间戳,13:44:23所以我可以做类似的事情

if(read==null OR if read 包含时间或分号){} else { SOP(read);}

4

4 回答 4

4

阅读所有行,忽略其他行。

int lineNum = 0;
String line = null;
while ( (line = reader.readLine() ) != null ) {
   lineNum++;
 if ( lineNum % 2 == 0 ) continue;
   //else deal with it
}

或者每个循环只调用readLine()两次,忽略第二次,并避免使用计数器(安全,因为所有对 readLine 的调用在到达流结束后都返回 null)。

编辑如果效率绝对是关键并且日期行具有固定长度的格式,您可以使用skip(15)或类似的方法有效地跳过您不关心的行。

于 2010-11-01T19:59:40.450 回答
2

当然,在你的-loopin.readLine ()结束之前放一个简单的东西会解决这个问题吗?for

IE:

for (linenum=0; linenum<20; linenum++) {

    read = in.readLine();
    if(read==null){} 
    else{
        System.out.println(read);  
    }
    in.readLine ();
}
于 2010-11-01T20:00:09.450 回答
0

你已经有一个 linecounter,所以如果你想使用其他每一行,使用模检查

if((linenum % 2) == 1){
     System.out.println(read);
}
于 2010-11-01T20:03:28.303 回答
0

每次阅读一行时,只需执行以下操作:

String str = read;
char[] all = str.toCharArray();
bool isInt = true;
for(int i = 0; i < all.length;i++) {
    if(!Character.isDigit(all[i])) {
        isInt = false;
    }
    else {
        isInt = true;
    }
}
if isInt {
    //INTEGER LINE
} else {
    //DO SOMETHING WITH THE TIME
}

这使代码动态化。如果文本文件发生更改,而整数出现在不同编号的行上,则您的代码可以保持不变。

于 2010-11-01T20:04:07.963 回答