如何将.txt文件转换为Android Java中的多行字符串

时间:2013-05-21 17:16:09

标签: java android

我已经坚持了几天,我只是找不到打开.txt文件的好方法。我需要将其转换为多行字符串并将其设置为textview。有人能帮帮我吗?

至于文件位置,我正在使用:

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

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

我通常可以将数据读入文件输入流,但如果我尝试使用它做任何事情,我会收到很多错误,不会让我的应用程序运行。

3 个答案:

答案 0 :(得分: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();
    }

答案 1 :(得分:0)

使用Apache Commons 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

答案 2 :(得分: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();
    }
}