1. Read TXT content:
Publicstring Gettxt (String uri) {string content=""; if(!"". Equals (URI) && uri! =NULL){ Try{File File=NewFile (URI);//Store AddressInputStream in=Newfileinputstream (file); byte[] B =New byte[3]; In.read (b);//ReadInputStreamReader read2; //determine the encoding format by byteString coding= ""; if(B[0] = = -17 && b[1] = = -69 && b[2] = = 65) {read2=NewInputStreamReader (In, "UTF-8");//Utf-8Coding= "UTF-8"; }Else{read2=NewInputStreamReader (In, "GBK");//Other CodesCoding= "GBK"; } BufferedReader Read=NewBufferedReader (READ2); String DDD= ""; intD=0; StringBuilder Str=NewStringBuilder (); while((Ddd=read.readline ())! =NULL){//Loop Get contentcontent+=DDD; Str.append (DDD); D++; } read2.close (); Read.close (); In.close (); } Catch(IOException e) {e.printstacktrace (); } } returncontent; }
2. Modify the specified content
InputStream in=Newfileinputstream (file); byte[] B =New byte[3]; In.read (b);//ReadInputStreamReader read2; //determine the encoding format by byteString coding= ""; if(B[0] = = -17 && b[1] = = -69 && b[2] = = 65) {read2=NewInputStreamReader (In, "UTF-8");//Utf-8Coding= "UTF-8"; }Else{read2=NewInputStreamReader (In, "GBK");//Other CodesCoding= "GBK"; } BufferedReader Read=NewBufferedReader (READ2); String DDD= ""; intD=0; StringBuilder Str=NewStringBuilder (); while((Ddd=read.readline ())! =NULL){//Loop Get contentcontent+=DDD; Str.append (DDD); D++; } read2.close (); Read.close (); In.close (); String STRB= Str.tostring (). Replace ("Content to modify", "Modified content"); Writer writer=NewBufferedWriter (NewOutputStreamWriter (NewFileOutputStream (URI), coding)); Writer.write (Strb.tochararray ()); Writer.flush (); Writer.close (); } Catch(IOException e) {e.printstacktrace (); } } returncontent; }
3.word Document Content Reading
Publicstring Getdocx (String uri) {//parse the docx template and get the Document objectxwpfdocument document; //get Xwpfrun object output entire text contentStringBuffer Temptext =NewStringBuffer (); Try{document=Newxwpfdocument (Poixmldocument.openpackage (URI)); //get the entire text objectList<xwpfparagraph> allparagraph =document.getparagraphs (); for(Xwpfparagraph xwpfparagraph:allparagraph) {List<XWPFRun> runlist =xwpfparagraph.getruns (); for(Xwpfrun xwpfrun:runlist) {temptext.append (xwpfrun.tostring ()); } } //Store the new address of the documentString newpath= ""; //Read source document content to new documentFile File =NewFile (NewPath); if(!File.getparentfile (). exists ()) {File.getparentfile (). mkdir (); File.getparentfile (). CreateNewFile (); } FileOutputStream Stream=NewFileOutputStream (NewPath); document.write (stream);//write New document Stream.Close (); } Catch(IOException e) {//TODO auto-generated Catch blockE.printstacktrace (); }
Document Contentreturntemptext.tostring (); }
Java file read (word,txt)