2013-06-06 300 views
0

我有以下格式如何从特定行开始读取.txt文件?

x  y 
3  8 
mz int 
200.1 3 
200.3 4 
200.5 5 
200.7 2 

等的文本文件。现在在这个文件中,我想将x和y值保存在两个不同的变量中,并将mz和int值保存在两个不同的数组中。我如何用Java读取这样的文件?

+1

https://github.com/kumarsaurabh20/Programming_Test/blob/master/network_prog_Java/FileReaderExamples/src/FileParseTestII.java – JstRoRR

回答

0

格式是否固定?如果是,那么你可以跳过第一行,读下一行,将它分开并分配给两个变量。

然后你可以跳过下一行并分割下一行并分配给数组。

+0

是的。格式是固定的。 – novicegeek

0
import java.io.BufferedReader; 
import java.io.FileReader; 
import java.util.ArrayList; 
import java.util.List; 


public class Demo { 

    public static void main(String[] args){ 
     BufferedReader reader = null; 
     String line = null; 
     List<String> list1 = new ArrayList<String>(); 
     List<String> list2 = new ArrayList<String>(); 
     try { 
      reader = new BufferedReader(new FileReader("c:\\file.txt")); 
      int i = 0; 
      while ((line = reader.readLine()) != null) { 
       i ++ ; 
       if(i > 3){ 
        String temp1 = line.split(" ")[0]; 
        String temp2 = line.split(" ")[1]; 
        list1.add(temp1); 
        list2.add(temp2); 
       } 
      } 
     } catch (Exception e) { 
      e.printStackTrace(); 
     } finally { 
      if(reader != null) { 
       try { 
        reader.close(); 
       } catch (Exception e) { 
        e.printStackTrace(); 
       } 
      } 
     } 
     System.out.println(list1); 
     System.out.println(list2); 
    } 
} 

顺便说一句:这里是10 golden rules of asking questions in the OpenSource community

+0

非常感谢你! – novicegeek