2013-05-14 42 views
-2

我有文本文件,該文件是包含:

「我有3個蘋果和香蕉1
所有的人有4輛車,至少。」從文本文件和工作獲取整數數組列表在Java

我想讀取這個.txt文件並從中獲取整數。我將在arrayList中讀取整數變量。

public class dedede { 
    public static void al() throws Exception { 

     File f = new File("C:\\users\\sony\\Desktop\\456.txt"); 

     try { 
      FileReader islem = new FileReader(f); 

      char data[] = new char[(int) f.length()]; 

      islem.read(data); 
      String metin = new String(data); 

      ArrayList<Integer> yapi = new<Integer> ArrayList(); 

      StringTokenizer s = new StringTokenizer(metin); 

      String dizi[] = new String[s.countTokens()]; 

      int i = 0; 
      while (s.hasMoreTokens()) { 
       dizi[i] = s.nextToken(); 
       i++; 
      } 

      for (int c = 0; c < dizi.length; c++) { 
       if (Integer.parseInt(dizi[c]) > 0) { 
        yapi.add(Integer.parseInt(dizi[c])); 
       } 

      } 

      System.out.println(yapi); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 

    } 

    public static void main(String[] args) throws Exception { 
     al(); 
    } 
} 
+1

什麼問題/問題,你遇到? – 2013-05-14 17:27:41

+0

我想編程讀取文件識別整數並將它們存儲在一個數組中。 – 2013-05-14 17:34:56

+1

除了你的代碼之外,你應該給出一些關於你在運行時遇到的問題或者你對結果有任何疑問的指示。 – 2013-05-14 17:36:17

回答

2

試試這個:

static ArrayList<Integer> al = new ArrayList<Integer>(); 

public static void main(String[] args) { 

    try { 
     File file = new File("C:\\users\\sony\\Desktop\\456.txt"); 
     BufferedReader in = new BufferedReader(new FileReader(file)); 
     String s; 
     while ((s = in.readLine()) != null) { 
      findInteger(s); 
     } 
     in.close(); 
    } catch (IOException e) { 
     System.out.println("File Read Error: " + e.getMessage()); 
    } 
    System.out.println("Integers: " + al); 
} 

private static void findInteger(String s){ 
    String [] parts = s.split(" "); 

    for (int i = 0; i < parts.length; i++) { 
     try{ 
      int j = Integer.parseInt(parts[i]); 
      al.add(j); 
     } catch (Exception e){} 
    } 
} 
+1

謝謝。你一直很有幫助我只是錯過了一些非常簡單的東西:) – 2013-05-14 17:50:18