【背景】
一个android项目中,需要读取一个文件的内容,读出来放到对应的一个String类型的变量中。
【解决过程】
1.其中,我之前已有一个函数outputStringToFile,用于写字符串到文件中:
1 2 3 4 5 6 | /* Method1 */ File newTextFile = new File(fullFilename); FileWriter fw; fw = new FileWriter(newTextFile); fw.write(strToOutput); fw.close(); |
现在需要去读文件,得到文件的内容,即字符串。
2.参考:
What is simplest way to read a file into String in java
Java : How To Read a Complete Text File into a String
但是没搞定。
3.再去参考:
写成对应代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | public static String readFileContentStr(String fullFilename) { String readOutStr = null ; try { BufferedReader bufReader = new BufferedReader( new FileReader(fullFilename)); String line = "" ; while ( ( line = bufReader.readLine() ) != null ) { readOutStr += line; } bufReader.close(); Log.d( "readFileContentStr" , "Successfully to read out string from file " + fullFilename); } catch (IOException e) { readOutStr = null ; //e.printStackTrace(); Log.d( "readFileContentStr" , "Fail to read out string from file " + fullFilename); } return readOutStr; } |
结果是:
好像是丢失了换行了
或者是:
没有正确识别UTF-8
所以再去试试别的。
4.后来是参考:
How to create a Java String from the contents of a file?
代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 | public static String readFileContentStr(String fullFilename) { String readOutStr = null ; try { // //BufferedReader bufReader = new BufferedReader(new FileReader(fullFilename)); // InputStreamReader isr = new InputStreamReader(new FileInputStream(fullFilename), "UTF-8"); // BufferedReader bufReader = new BufferedReader(isr); // // String lineSeparator = System.getProperty("line.separator"); // // String line = ""; // while( ( line = bufReader.readLine() ) != null) // { // readOutStr += line + lineSeparator; // } // bufReader.close(); DataInputStream dis = new DataInputStream( new FileInputStream(fullFilename)); try { long len = new File(fullFilename).length(); if (len > Integer.MAX_VALUE) throw new IOException( "File " +fullFilename+ " too large, was " +len+ " bytes." ); byte [] bytes = new byte [( int ) len]; dis.readFully(bytes); readOutStr = new String(bytes, "UTF-8" ); } finally { dis.close(); } Log.d( "readFileContentStr" , "Successfully to read out string from file " + fullFilename); } catch (IOException e) { readOutStr = null ; //e.printStackTrace(); Log.d( "readFileContentStr" , "Fail to read out string from file " + fullFilename); } return readOutStr; } |
在Android AVD模拟器上运行效果:
读取140KB的文件,耗时200ms左右。
速度还是不错的。
【总结】
java语言,虽然号称同样一件事情,有多种方案,
但是对于,从文件中读取内容为字符串,这种简单的事情,结果竟然没有很好的,便于使用的方案
从这点来说,更加觉得java语言,越来越挫了。
注:
关于java的吐槽,见:
转载请注明:在路上 » 【已解决】android中读取文件内容为字符串String类型变量