2012-02-29 55 views
0
private static int count = 0; 

    public static String[] play()throws Exception{ 
     File file=new File("E:/proj/"+count+".bin"); 
     FileInputStream fin=new FileInputStream("E:/proj/"+count+".bin"); 

     //reading the byte content of the bin files 
     byte fileContent[] = new byte[(int)file.length()]; 
     fin.read(fileContent); 

     //storing the deserialized object that is returned to an object. 
     Object obj=serializer.toObject(fileContent); 

     //converting the obtained object to string 
     String word=obj.toString(); 
     String[] args=new String[]{word}; 
     count++; 
     return args ;   
    } 

這段代碼實際上應該閱讀所有存在於指定路徑的bin文件,並最終將其轉換爲字符串,所有的byte[]轉換爲字符串不同的字符串元素存儲在string[]回報string[]。雖然由於計數器而讀取所有bin文件,但它只返回它讀取的第一個二進制文件的字符串。閱讀並返回多個Bin文件

即使dosent這個修改後的版本似乎工作。我想它讀取所有的bin文件,但只返回讀取的最後一個bin文件的字符串。我試圖出去了,存儲所有字符串元素的string[]並返回string[]到另一個調用函數。

public static String[] play(){ 
    int i = 1; 
    String[] args=null;; 
    String result = null; 
    while (true) { 
     try { 
      result += processFile(i++); 
      args=new String[]{result}; 
     } 
      catch (Exception e) { 
      System.out.println("No more files"); 
      break; 
     } 
    } 
    return args; 
}  

private static String processFile(int fileNumber) throws Exception { 
    File file=new File("E:/proj/"+fileNumber+".bin"); 
    FileInputStream fin=new FileInputStream("E:/proj/"+fileNumber+".bin"); 

    //reading the byte content of the bin files 
    byte fileContent[] = new byte[(int)file.length()]; 
    fin.read(fileContent); 

    //storing the deserialized object that is returned, to an object. 
    Object obj=serializer.toObject(fileContent); 

    //converting the obtained object to string 
    String word=obj.toString(); 
    return word; 
} 
+0

是從循環內調用play()方法嗎?你可以顯示其餘的代碼? – assylias 2012-02-29 10:34:40

+0

hii Assylias ..播放方法不在循環內調用。它只是調用另一個類... – kuki 2012-02-29 15:28:19

回答

0

如果我理解你的要求清楚,你可以試着改變你的代碼是這樣的:

List<String> args = new ArrayList<String>(); 
    while (true) { 
     try { 
      args.add(processFile(i++)); 
     } 
     catch (Exception e) { 
      // your code 
     } 
    } 
    String[] array = args.toArray(new String[0]); 
+0

斐伊川kuldeep ...謝謝... TONN它的工作! :) – kuki 2012-02-29 16:09:30

+0

@kuki,不要忘了「接受的答案:」如果它幫助你解決問題否則你的接受率會下降。 – 2012-03-01 04:31:41

0

還有您剛剛發佈的代碼的幾個問題: - 結果被初始化爲null,所以你代碼將在第一個循環中拋出一個NPE。 - 假設你初始化它正確(在你的情況「」),參數表是使你失去你從以前的循環獲得的信息重新分配給每個循環的新數組。

如果你希望你的play()方法返回一個數組,數組中的每個項目是一個文件的內容,這應該工作。如果你想要不同的東西,你需要更清楚地解釋你的需求。

public static String[] play() { 
    int i = 1; 
    List<String> files = new ArrayList<String>(); 
    while (true) { 
     try { 
      files.add(processFile(i++)); 
     } catch (Exception e) { 
      System.out.println("No more files"); 
      break; 
     } 
    } 
    return files.toArray(new String[0]); 
}