代码之家  ›  专栏  ›  技术社区  ›  razshan

如何使用Java从文本文件中读取奇数行?

  •  1
  • razshan  · 技术社区  · 14 年前

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

    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(); 
    } 
    }
    

    从现在起,它将读取所有(奇数和偶数)行,直到不再有可读取的行为止(空)

    因为我的偶数行是时间戳 13:44:23 我能做点什么吗

    时间或分号{}其他{ SOP(读);}

    4 回复  |  直到 14 年前
        1
  •  2
  •   Philip    14 年前

    当然是简单的 in.readLine () 就在你的 for

    即。:

    for (linenum=0; linenum<20; linenum++) {
    
        read = in.readLine();
        if(read==null){} 
        else{
            System.out.println(read);  
        }
        in.readLine ();
    }
    
        2
  •  4
  •   Mark Peters    14 年前

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

    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) 或者类似于有效地跳过你不在乎的那一行。

        3
  •  0
  •   Thediabloman    14 年前

    您已经有一个测线计数器,所以如果您想每隔一行使用一次,请使用模检查

    if((linenum % 2) == 1){
         System.out.println(read);
    }
    
        4
  •  0
  •   Scott    14 年前

    每次你读到一行字的时候就做这样的事情:

    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
    }
    

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