try { File sourceFile = new File("C:\Users\prize\Desktop\Demo1\盗墓笔记7.txt");//创建源文件 InputStream inputStream = new FileInputStream(sourceFile);//创建输入文件流 BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream)); //创建文本行缓存输入流 导入 缓存输入流 File targetFile = new File("F:\手机T卡资料\直接复制T卡\EBOOK\复制的书.txt"); //创建复制的目标文件 if (targetFile.exists()) { //判断文件是否存在 targetFile.delete(); //删除文件 targetFile.createNewFile(); //创建文件 }else { targetFile.createNewFile(); } OutputStream out = new FileOutputStream(targetFile); //创建输出文件流 BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(out)); //创建文本缓存输出流 导入 缓存输出流 String aString = null; //给一行的内容准备的String int i = 0; while ((aString = reader.readLine()) != null && i<20) { //读取一行,并且赋值给aString,然后在判断不是空值 //i++; //此处是为了输出指定数量行数写的 循环自增, writer.write(" "+aString); //将内容添加到输出流中 //System.out.println(aString); } writer.flush(); //刷新输出流 writer.close(); //关闭流 ,注意流的关闭顺序 out.close(); reader.close(); inputStream.close(); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); }
流文件
int len = 0; byte[] bytes = new byte[2048]; while ((len = fileInputStream.read(bytes)) != -1) { fileOutputStream.write(bytes, 0, len); fileOutputStream.flush(); } fileInputStream.close(); fileOutputStream.close();
批量处理文件:
public void fileList() { File inFile = new File("C:\Users\lenovo\Desktop\copy\color"); File [] files = inFile.listFiles(); for (int i = 0; i < files.length; i++) { files[i].delete(); System.out.println(files[i].toString()); }