1

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

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

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

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

我通常可以将数据读入文件输入流,但如果我尝试对它做任何事情,我会收到大量错误,甚至无法让我的应用程序运行。

4

3 回答 3

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();
    }
于 2013-05-21T17:18:36.953 回答
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

于 2013-05-21T17:20:07.790 回答
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();
    }
}
于 2013-05-21T17:21:22.493 回答