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 に答える
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 に答える
-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 に答える