我需要在android中加载一个xml文件作为String,这样我就可以将它加载到TBXML xml解析器库并解析它。我现在将文件读取为String的实现大约需要2秒,即使对于某些KB的非常小的xml文件也是如此。是否有任何已知的快速方法可以在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;
}
答案 0 :(得分:134)
最终使用的代码如下:
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;
}
答案 1 :(得分:14)
您可以使用org.apache.commons.io.IOUtils.toString(InputStream is, Charset chs)
来执行此操作。
e.g。
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回购看 - &gt; this link
对于直接jar下载,请参阅 - &gt; https://commons.apache.org/proper/commons-io/download_io.cgi
答案 2 :(得分:14)
重写了源自 - &gt;的方法集。 the accepted answer
@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;
}
答案 3 :(得分:4)
对于文件,我们事先知道大小,所以只需一次阅读!
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 = "";
}
}
答案 4 :(得分:0)
使用Kotlin非常简单:
val textFile = File(cacheDir, "/text_file.txt")
val allText = textFile.readText()
println(allText)
来自readText()
文档:
使用UTF-8或String作为字符串获取此文件的全部内容 指定的字符集。不建议在大文件上使用此方法。它 内部限制为2 GB文件大小。
答案 5 :(得分:0)
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;
}
答案 6 :(得分:-8)
这对我有用
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;
}