2013-05-21 62 views
1

我一直堅持這一兩天,我只是無法找到一個很好的方法來打開.txt文件。我需要將其轉換爲多行字符串並將其設置爲textview。有人能幫助我嗎?如何將.txt文件轉換爲Android中的多行字符串Java

爲文件的位置,我使用的是:

String saveLoc = Environment.getExternalStorageDirectory()+"/My Documents/"; 
public String title; 
public String Ftype = ".txt"; 

(saveLoc+title+Ftype) //is the file location. 

我可以正常讀取數據到文件輸入流,但如果我試圖用它做任何事情,我得到這不會錯誤的負載讓我的應用程序甚至運行。

回答

0
private String readTxt(){ 

InputStream inputStream = new FileInputStream("Text File Path Here"); 

    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); 

    int i; 
    try { 
    i = inputStream.read(); 
    while (i != -1) 
     { 
     byteArrayOutputStream.write(i); 
     i = inputStream.read(); 
     } 
     inputStream.close(); 
    } catch (IOException e) { 
    // TODO Auto-generated catch block 
    e.printStackTrace(); 
    } 

    return byteArrayOutputStream.toString(); 
    } 
+0

感謝回答得這麼快!但我不能使用預先定義的位置,程序打開用戶創建的文件,這就是爲什麼字符串'標題'留空。運行代碼塊的按鈕定義標題的值。 – user2406536

+0

這樣也沒有問題,您可以輕鬆地從外部存儲器讀取文件。 –

+0

哈哈怎麼樣?對不起,我對Android非常陌生,而且我對Java的這段時間並不熟悉。 – user2406536

0

使用Apache下議院IO FileUtils.readLines()

readLines public static List readLines(File file, Charset encoding) throws IOException Reads the contents of a file line by line to a List of Strings. The file is always closed. Parameters: file - the file to read, must not be null encoding - the encoding to use, null means platform default Returns: the list of Strings representing each line in the file, never null Throws: IOException - in case of an I/O error Since: 2.3

0
private static String readFile(String path) throws IOException 
{ 
    FileInputStream stream = new FileInputStream(new File(path)); 
    try { 
      FileChannel fc = stream.getChannel(); 
      MappedByteBuffer bb = fc.map(FileChannel.MapMode.READ_ONLY, 0, fc.size()); 
      /* Instead of using default, pass in a decoder. */ 
      return Charset.defaultCharset().decode(bb).toString(); 
     } 

    catch (IOException e) 
    { 
      e.printStackTrace(); 
    } 

    finally 
    { 
      stream.close(); 
    } 
} 
相關問題