java文件读取(word,txt)
Posted yogoo
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java文件读取(word,txt)相关的知识,希望对你有一定的参考价值。
1.读取txt内容:
public String getTxt(String uri){ String content=""; if(!"".equals(uri) && uri != null){ try { File file=new File(uri);//存放地址 InputStream in= new FileInputStream(file); byte[] b = new byte[3]; in.read(b);//读取 InputStreamReader read2; //通过字节判断编码格式 String coding=""; if (b[0] == -17 && b[1] == -69 && b[2] == -65){ read2 = new InputStreamReader(in,"UTF-8");//utf-8 coding="UTF-8"; }else { read2 = new InputStreamReader(in,"GBK");//其他编码 coding="GBK"; } BufferedReader read=new BufferedReader(read2); String ddd = ""; int d=0; StringBuilder str=new StringBuilder(); while((ddd=read.readLine())!=null){//循环获取内容 content+=ddd; str.append(ddd); d++; } read2.close(); read.close(); in.close(); } catch (IOException e) { e.printStackTrace(); } } return content; }
2.修改指定内容
InputStream in= new FileInputStream(file); byte[] b = new byte[3]; in.read(b);//读取 InputStreamReader read2; //通过字节判断编码格式 String coding=""; if (b[0] == -17 && b[1] == -69 && b[2] == -65){ read2 = new InputStreamReader(in,"UTF-8");//utf-8 coding="UTF-8"; }else { read2 = new InputStreamReader(in,"GBK");//其他编码 coding="GBK"; } BufferedReader read=new BufferedReader(read2); String ddd = ""; int d=0; StringBuilder str=new StringBuilder(); while((ddd=read.readLine())!=null){//循环获取内容 content+=ddd; str.append(ddd); d++; } read2.close(); read.close(); in.close(); String strb = str.toString().replace("要修改的内容", "修改后的内容"); Writer writer = new BufferedWriter( new OutputStreamWriter( new FileOutputStream(uri), coding)); writer.write(strb.toCharArray()); writer.flush(); writer.close(); } catch (IOException e) { e.printStackTrace(); } } return content; }
3.word文档内容读取
public String getDocx(String uri){ //解析docx模板并获取document对象 XWPFDocument document; //获取XWPFRun对象输出整个文本内容 StringBuffer tempText = new StringBuffer(); try { document = new XWPFDocument(POIXMLDocument.openPackage(uri)); //获取整个文本对象 List<XWPFParagraph> allParagraph = document.getParagraphs(); for (XWPFParagraph xwpfParagraph : allParagraph) { List<XWPFRun> runList = xwpfParagraph.getRuns(); for (XWPFRun xwpfRun : runList) { tempText.append(xwpfRun.toString()); } } //存放文档新地址 String newPath=""; //读取源文档内容到新文档 File file = new File(newPath); if(!file.getParentFile().exists()){ file.getParentFile().mkdir(); file.getParentFile().createNewFile(); } FileOutputStream stream = new FileOutputStream(newPath); document.write(stream);//写入新文档 stream.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); }
//文档内容 return tempText.toString(); }
以上是关于java文件读取(word,txt)的主要内容,如果未能解决你的问题,请参考以下文章