日期:2014-05-20 浏览次数:20702 次
package test; import java.io.ByteArrayInputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; public class IoTest { public StringBuffer fileDoc(File path,StringBuffer sb){ //目录列表数组 File[] files = path.listFiles(); //字节流读取 FileInputStream fileInputStream = null; for(File file1 : files){ if(file1.isDirectory()){//如果是目录 //递归 fileDoc(file1,sb); }else{ try { fileInputStream = new FileInputStream(file1); int size = fileInputStream.available(); byte[] tempByte = new byte[size]; if(fileInputStream.read(tempByte) != size){ System.out.println("文件读取失败!!!"); }else{ //内容转换 String change = new String(tempByte,"utf-8"); sb.append(change); } } catch (Exception e) { e.printStackTrace(); } } } return sb; } //保存数据 public static void saveDataForTxt(StringBuffer sbStr){ //总数据 String allStr = sbStr.toString(); byte[] bytes = allStr.getBytes(); //将数据放到字节输入流中 ByteArrayInputStream bais = new ByteArrayInputStream(bytes); //1k的数据 byte[] newbytes = new byte[1024]; int len = 0; int i = 1; try { while((len = bais.read(newbytes)) != -1){ File file = new File("d:\\java\\"+i+".txt"); new FileOutputStream(file).write(newbytes,0,len); i++; } } catch (Exception e) { e.printStackTrace(); } } public static void main(String[] args) { String path = "d:\\TDDownload\\Test1"; File file = new File(path); //要得到的数据集合(初始) StringBuffer sbTemp = new StringBuffer(); sbTemp = new IoTest().fileDoc(file,sbTemp); saveDataForTxt(sbTemp); } }