63

我需要在 android 中将 xml 文件作为字符串加载,以便将其加载到 TBXML xml 解析器库并解析它。即使对于一些 KB 的非常小的 xml 文件,我现在必须以字符串形式读取文件的实现需要大约 2 秒。是否有任何已知的快速方法可以在 Java/Android 中将文件作为字符串读取?


这是我现在的代码:

public static String readFileAsString(String filePath) {
    String result = "";
    File file = new File(filePath);
    if ( file.exists() ) {
        //byte[] buffer = new byte[(int) new File(filePath).length()];
        FileInputStream fis = null;
        try {
            //f = new BufferedInputStream(new FileInputStream(filePath));
            //f.read(buffer);

            fis = new FileInputStream(file);
            char current;
            while (fis.available() > 0) {
                current = (char) fis.read();
                result = result + String.valueOf(current);
            }
        } catch (Exception e) {
            Log.d("TourGuide", e.toString());
        } finally {
            if (fis != null)
                try {
                    fis.close();
                } catch (IOException ignored) {
            }
        }
        //result = new String(buffer);
    }
    return result;
}
4

7 回答 7

157

最终使用的代码如下:

http://www.java2s.com/Code/Java/File-Input-Output/ConvertInputStreamtoString.htm

public static String convertStreamToString(InputStream is) throws Exception {
    BufferedReader reader = new BufferedReader(new InputStreamReader(is));
    StringBuilder sb = new StringBuilder();
    String line = null;
    while ((line = reader.readLine()) != null) {
      sb.append(line).append("\n");
    }
    reader.close();
    return sb.toString();
}

public static String getStringFromFile (String filePath) throws Exception {
    File fl = new File(filePath);
    FileInputStream fin = new FileInputStream(fl);
    String ret = convertStreamToString(fin);
    //Make sure you close all streams.
    fin.close();        
    return ret;
}
于 2012-11-13T08:49:24.050 回答
17

你可以用它org.apache.commons.io.IOUtils.toString(InputStream is, Charset chs)来做到这一点。

例如

IOUtils.toString(context.getResources().openRawResource(<your_resource_id>), StandardCharsets.UTF_8)

要添加正确的库:

将以下内容添加到您的 app/build.gradle 文件中:

dependencies {
    compile 'org.apache.directory.studio:org.apache.commons.io:2.4'
}

或者对于 Maven 存储库,请参见 ->这个链接

对于直接 jar 下载,请参阅-> https://commons.apache.org/proper/commons-io/download_io.cgi

于 2013-06-27T11:13:51.760 回答
16

重新设计了源自 ->接受的答案的方法集

@JaredRummler 对您的评论的回答:

以字符串形式读取文件

这不会在字符串末尾添加一个额外的新行吗?

为了防止在末尾添加换行符,您可以在第一个循环期间使用布尔值集,就像在代码示例中一样Boolean firstLine

public static String convertStreamToString(InputStream is) throws IOException {
   // http://www.java2s.com/Code/Java/File-Input-Output/ConvertInputStreamtoString.htm
    BufferedReader reader = new BufferedReader(new InputStreamReader(is));
    StringBuilder sb = new StringBuilder();
    String line = null;
    Boolean firstLine = true;
    while ((line = reader.readLine()) != null) {
        if(firstLine){
            sb.append(line);
            firstLine = false;
        } else {
            sb.append("\n").append(line);
        }
    }
    reader.close();
    return sb.toString();
}

public static String getStringFromFile (String filePath) throws IOException {
    File fl = new File(filePath);
    FileInputStream fin = new FileInputStream(fl);
    String ret = convertStreamToString(fin);
    //Make sure you close all streams.
    fin.close();
    return ret;
}
于 2016-04-18T18:04:13.780 回答
7

如果你使用 Kotlin,这很容易:

val textFile = File(cacheDir, "/text_file.txt")
val allText = textFile.readText()
println(allText)

来自readText()文档:

使用 UTF-8 或指定字符集以字符串形式获取此文件的全部内容。不建议在大文件上使用此方法。它具有 2 GB 文件大小的内部限制。

于 2019-12-18T15:30:37.670 回答
6

对于文件,我们事先知道其大小,因此只需一次性阅读!

String result;
File file = ...;

long length = file.length();
if (length < 1 || length > Integer.MAX_VALUE) {
    result = "";
    Log.w(TAG, "File is empty or huge: " + file);
} else {
    try (FileReader in = new FileReader(file)) {
        char[] content = new char[(int)length];

        int numRead = in.read(content);
        if (numRead != length) {
            Log.e(TAG, "Incomplete read of " + file + ". Read chars " + numRead + " of " + length);
        }
        result = new String(content, 0, numRead);
    }
    catch (Exception ex) {
        Log.e(TAG, "Failure reading " + this.file, ex);
        result = "";
    }
}
于 2014-08-14T18:33:47.683 回答
-1
public static String readFileToString(String filePath) {
    InputStream in = Test.class.getResourceAsStream(filePath);//filePath="/com/myproject/Sample.xml"
    try {
        return IOUtils.toString(in, StandardCharsets.UTF_8);
    } catch (IOException e) {
        logger.error("Failed to read the xml : ", e);
    }
    return null;
}
于 2020-06-16T14:19:22.353 回答
-12

这对我有用

i use this path

String FILENAME_PATH =  "/mnt/sdcard/Download/Version";

public static String getStringFromFile (String filePath) throws Exception {
    File fl = new File(filePath);
    FileInputStream fin = new FileInputStream(fl);
    String ret = convertStreamToString(fin);
    //Make sure you close all streams.
    fin.close();        
    return ret;

}
于 2014-07-19T16:11:09.977 回答