java - 安卓。从文件中读取内容

标签 java android

我正在使用下一个方法从文件中读取内容。这里的问题是我仅限于为 inputBuffer 指定的字符数(在本例中为 1024)。

首先,如果内容长度小于1024个字符,我会得到很多空白字符,我需要使用trim来删除它们。

其次,也是更重要的一点,我想读取文件的全部内容,即使它超过 1024 个字符,并将其插入到 String 对象中。我知道我不应该使用 .available 方法来确定文件中是否有更多数据,因为它不准确或类似的东西。

关于我应该如何去做这件事有什么想法吗?

public String getContent( String sFileName )
{
    //Stop in case the file does not exists
    if ( !this.exists( sFileName ) )
        return null;

    FileInputStream fIn = null;

    InputStreamReader isr = null;

    String data = null;

    try{

        char[] inputBuffer = new char[1024];

        fIn = _context.openFileInput(sFileName);

        isr = new InputStreamReader(fIn);

        isr.read(inputBuffer);

        data = new String(inputBuffer);

        isr.close();

        fIn.close();

    }catch(IOException e){

        e.printStackTrace(System.err);
        return null;

    }

    return data.trim();
}

最佳答案

您可以在分配缓冲区之前读取#/bytes:

// Poor
char[] inputBuffer = new char[1024];
fIn = _context.openFileInput(sFileName);
isr = new InputStreamReader(fIn);

// Better
long nbytes = new File(sFileName).length();
char[] inputBuffer new char[nbytes];
isr = new InputStreamReader (
  _context.openFileInput (sFileName));

另一种解决方案是将输入作为字符串读取,一次一行。

关于java - 安卓。从文件中读取内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12328555/

相关文章:

android - 如何在 Android 中的 Thread 中使用 toast 消息

JavaFx 自定义设计按钮在使用的应用程序中单击检测

java - 新错误 java.lang.IllegalStateException : Can not perform this action after onSaveInstanceState

java - 使用 Glide 从 URL 加载图像但不带扩展名

java - 无法修复 Fragment NullPointerException 中的 Map Fragment

android - 如何根据 android 中的谷歌地图不同缩放级别调整谷歌地图标记的大小

c# - 是否有 C# 等效于 Java 中的 File.separator

java - 使用常见 OpenOption 组合的最快方法

java - 操作 XmlSeeAlso 注释的结果

android - Google 附近连接 2.0 功能