Read directly with the byte stream, can retain the original format, in the assembly of strings can be encoded to utf-8 to prevent garbled, but according to the size of the cache byte array, there will be some characters garbled situation
Public StaticString Readtotext (String filePath) {//read by Byte stream preserves the original format, but it is partially garbled and varies according to the size of the byte array that is read every timeStringBuffer txtcontent =NewStringBuffer (); byte[] B =New byte[2048]; InputStream in=NULL; Try{ in=NewFileInputStream (FilePath); intN; while((n = in.read (b))! =-1) {txtcontent.append (NewString (b, 0, N, "Utf-8"))); } in.close (); } Catch(FileNotFoundException e) {e.printstacktrace (); } Catch(IOException e) {e.printstacktrace (); } finally { if(In! =NULL) { Try{in.close (); } Catch(IOException e) {e.printstacktrace (); } } } returntxtcontent.tostring (); }
Using the character stream of the ReadLine read out can not preserve the original format of the document, the space in the line is invalid. But it's not garbled. The final solution is to use this method and then manually stitch the line break. The code is as follows:
Public StaticString Readtxt (string path) {//read by row, cannot preserve formatting such as line breaks, so you need to manually add a line break. //String result = "";StringBuffer txtcontent =NewStringBuffer (); File File=NewFile (path); Try { intLen = 0; FileInputStream in=Newfileinputstream (file); InputStreamReader Reader=NewInputStreamReader (In, "Utf-8"); BufferedReader BR=NewBufferedReader (reader); String s=NULL; while((s = br.readline ())! =NULL) { if(len! = 0) {//problems with line breaks, the first line does not wrapTxtcontent.append (NewString ("\ r \ n" + s). GetBytes (), "Utf-8")); } Else{txtcontent.append (NewString (S.getbytes (), "Utf-8")); } Len++; } reader.close (); In.close (); } Catch(Unsupportedencodingexception |FileNotFoundException e) { //TODO auto-generated Catch blockE.printstacktrace (); } Catch(IOException e) {//TODO auto-generated Catch blockE.printstacktrace (); } /*try {bufferedreader br = new BufferedReader (new FileReader (path)); String s = null; while ((S=br.readline ())!=null) {result = result + "\ n" + s; }} catch (FileNotFoundException e) {//TODO auto-generated catch block E.printstacktrace (); } catch (IOException e) {//TODO auto-generated catch block E.printstacktrace (); }*/ returntxtcontent.tostring (); }
Android Read txt to string