2013-07-03 45 views
0
  try { 
       inputStream = assetManager.open("model.obj"); 
       if (inputStream != null) 
       { 
        Log.d("aaa", "It worked!"); 

        //Get length of inputstream 
        for(int i=0;i<inputStream.available();i++) 
        { 

        } 
        //String line = null, input=""; 

        /*while((line = inputStream.) != null) 
        { 
         input += line; 
        }*/ 
       } 
      } catch (IOException e) { 
       e.printStackTrace(); 
      } 

我有inputStream看起來像它是原始字節,我可以從inputStream獲取一些字節並循環。 我實際上想要做的是循環讀取文件中的每一行,並將其分割爲空格字符,如split(「」)。 InputStream可以轉換成更多的形式讀取線條和空間字符分裂嗎?Android inputStream。檢查換行符和拆分

謝謝!

+0

http://www.mkyong.com/java/how-to-convert-inputstream-to-string-in-java/。試試這個 – Raghunandan

回答

2

您可以使用BufferedReader類的readLine()方法如下來檢測是否存在新行。

InputStream is = new ByteArrayInputStream("file content".getBytes()); 

//read it with BufferedReader 
BufferedReader br = new BufferedReader(new InputStreamReader(is)); 

StringBuilder sb = new StringBuilder(); 

String line; 
while ((line = br.readLine()) != null) 
{ 
    // perform your task here 
}  
+0

我建議你避免在不指定編碼的情況下演示如何使用'String.getBytes()'和'new InputStreamReader'。它總是*一個好主意來指定編碼。 –

+0

@JonSkeet,謝謝你照顧它。 – Lucifer

1

Scanner班會派上用場。您可以將輸入流傳遞給掃描器類,然後輕鬆地將它們作爲行。

try { 
    inputStream = assetManager.open("model.obj"); 
    Scanner sc; 
    if (inputStream != null) { 
    sc = new Scanner(inputStream); // also has a constructor which take in a charsetName 
    while(sc.hasNextLine()) { 
     sc.nextLine(); 
    } 
    } 
} catch (IOException e) { 
    e.printStackTrace(); 
} 
0

這是從資產代碼讀取文件....

AssetManager assetManager = getResources()getAssets(); InputStream inputStream = null;

try { 
    inputStream = assetManager.open("foo.txt"); 
     if (inputStream != null) 
      Log.d(TAG, "It worked!"); 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } 

不要使用InputStream is = assetManager.open(「assets/foo.txt」);

Try this link分裂,你需要的東西...

1
BufferedReader br = new BufferedReader(new InputStreamReader(inputStream, "UTF-8")); 
String line; 
while ((line = br.readLine()) != null) 
{ 
    // perform your task here 
}