2013-06-06 126 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