问题描述
|
几乎每个代码示例都逐行读取TXT文件并将其存储在String数组中。我不需要逐行处理,因为我认为这对我的要求来说是不必要的资源浪费:我要做的就是快速,有效地将.txt内容转储到单个String中。下面的方法可以完成这项工作,但是有一个缺点:
(HTML标记)。 先感谢您。
private static String readFileAsstring(String filePath) throws java.io.IOException{
byte[] buffer = new byte[(int) new File(filePath).length()];
BufferedInputStream f = null;
try {
f = new BufferedInputStream(new FileInputStream(filePath));
f.read(buffer);
if (f != null) try { f.close(); } catch (IOException ignored) { }
} catch (IOException ignored) { System.out.println(\"File not found or invalid path.\");}
return new String(buffer);
}
缺点是换行符会转换成较长的空格,例如\““。”。
我希望将换行符从\\ n或\\ r转换为(HTML标记)。 先感谢您。
解决方法
如何使用扫描仪并自己添加换行符:
sc = new java.util.Scanner (\"sample.txt\")
while (sc.hasNext ()) {
buf.append (sc.nextLine ());
buf.append (\"<br />\");
}
我看不到您从哪里得到长空间。
,您可以直接读入缓冲区,然后从缓冲区创建一个字符串:
File f = new File(filePath);
FileInputStream fin = new FileInputStream(f);
byte[] buffer = new byte[(int) f.length()];
new DataInputStream(fin).readFully(buffer);
fin.close();
String s = new String(buffer,\"UTF-8\");
,您可以添加以下代码:
return new String(buffer).replaceAll(\"(\\r\\n|\\r|\\n|\\n\\r)\",\"<br>\");
这是你想要的?
,该代码将读取文件中显示的文件内容-包括换行符。
如果要将中断更改为其他内容,例如以html等显示,则需要对其进行后期处理,或者通过逐行读取文件来进行处理。由于您不希望使用后者,因此您可以按照以下方法替换您的退货:
return (new String(buffer)).replaceAll(\"\\r[\\n]?\",\"<br>\");
,StringBuilder sb = new StringBuilder();
try {
InputStream is = getAssets().open(\"myfile.txt\");
byte[] bytes = new byte[1024];
int numRead = 0;
try {
while((numRead = is.read(bytes)) != -1)
sb.append(new String(bytes,numRead));
}
catch(IOException e) {
}
is.close();
}
catch(IOException e) {
}
您得出的String
:String result = sb.toString();
然后替换此result
中的任何内容。
,我同意@Sanket Patel的一般方法,但是使用Commons I / O可能需要File Utils。
所以您的代码字看起来像:
String myString = FileUtils.readFileToString(new File(filePath));
还有另一个版本可以指定备用字符编码。
,您应该尝试org.apache.commons.io.IOUtils.toString(InputStream is)以String形式获取文件内容。在那里,您可以传递InputStream对象,该对象将从中获取
getAssets().open(\"xml2json.txt\") *<<- belongs to Android,which returns InputStream*
在您的活动中。要获取String,请使用以下代码:
String xml = IOUtils.toString((getAssets().open(\"xml2json.txt\")));
所以,
String xml = IOUtils.toString(*pass_your_InputStream_object_here*);