Java文件操作,共实现了文件复制(单个文件和多层目录文件),文件移动(单个文件和多层目录文件),文件删除(单个文件和多层目录文件),文件压缩 (单个文件),文件解压(单个文件),文件分割(将一个大文件分割为若干个小文件),文件组合(将多个文件组合到一个文件中)。

package ttstudy.io;

import java.io.*;

import java.util.*;

import java.util.zip.*;

public class FileManager {

private static ArrayList<File> lsFiles = new ArrayList<File>();

private static FileInputStream fis = null;

private static FileOutputStream fos = null;

/**

* list all files

* @param path

* @return ArrayList<File>

* @throws FileNotFoundException

*/

public static ArrayList<File> listAllFiles(String path) throws FileNotFoundException {

File file = new File(path);

File[] f = file.listFiles();

for(int i=0; i<f.length; i++) {

lsFiles.add(f[i]);

//If the current file is a directory, Recursion listed catalogue of the files

if(f[i].isDirectory()) {

listAllFiles(f[i].getAbsolutePath());

}

}

return lsFiles;

}

/**

* copy srcFile to desFile

* @param srcFile

* @param desFile

* @throws FileNotFoundException

*/

public static void copyFile(String srcFile, String desFile) throws FileNotFoundException, IOException {

fis = new FileInputStream(new File(srcFile));

fos = new FileOutputStream(new File(desFile));

byte[] buf = new byte[1024];

int len = 0;

while((len=fis.read(buf)) != -1) {

fos.write(buf, 0, len);

}

fos.close();

fis.close();

}

/**

* copy all files in srcFile to desFile

* @param srcFile

* @param desFile

* @throws FileNotFoundException

*/

public static void copyFiles(String srcFile, String desFile) throws FileNotFoundException, IOException {

ArrayList<File> lsFiles = listAllFiles(srcFile);

for(int i=0; i<lsFiles.size(); i++) {

File curFile = lsFiles.get(i);

if(curFile.isDirectory()) {

new File(desFile+curFile.getAbsolutePath().substring(srcFile.length())).mkdir();

} else {

copyFile(curFile.getAbsolutePath(), new File(desFile+curFile.getAbsolutePath().substring(srcFile.length())).getAbsolutePath());

}

}

}

/**

* Split a file into multiple files

* @param srcFile

* @param desDir   分割后文件存放的位置,是一个目录

* @param n

* @return

* @throws FileNotFoundException

*/

public static File[] splitFile(String srcFile, String desDir, int part) throws FileNotFoundException, IOException {

File[] rsFile = new File[part];

File f = new File(srcFile);

long partLen = f.length()/part;     //part等分

int perLen = 2;

if(partLen > 1024) {

perLen = 512;

} else {

perLen = 2;

}

byte[] buf = new byte[perLen];

fis = new FileInputStream(f);

for(int i=0; i<part; i++) {

int pos = f.getName().lastIndexOf('.');

File partFile = new File(desDir+"/"+f.getName().substring(0, pos)+(i+1)+f.getName().substring(pos));

fos = new FileOutputStream(partFile);

rsFile[i] = partFile;

long m = partLen/perLen;

for(int j=0; j<m; j++) {

int len = 0;

if((len=fis.read(buf)) != -1) {

fos.write(buf, 0, len);

}

}

}

//由于整除原因,可能导致最后一部分没有写入到文件中,因此需要补充下面内容

int nn= 0;

if((nn=fis.read(buf)) != -1) {

fos.write(buf, 0, nn);

}

fos.close();

fis.close();

return rsFile;

}

/**

* Combination of multiple files into one file

* @param srcFile

* @param desFile

* @return

* @throws FileNotFoundException

* @throws IOException

*/

public static File mergeFile(File[] srcFile, String desFile) throws FileNotFoundException, IOException {

File rsFile = new File(desFile);

fos = new FileOutputStream(new File(desFile));

byte[] buf = new byte[1024];

int len = 0;

for(int i=0; i<srcFile.length; i++) {

fis = new FileInputStream(srcFile[i]);

while((len=fis.read(buf)) != -1) {

fos.write(buf, 0, len);

}

fis.close();

}

if(fos != null) {

fos.close();

}

if(fis != null) {

fis.close();

}

return rsFile;

}

/**

* delete a file

* @param srcFile

* @throws FileNotFoundException

* @throws IOException

*/

public static void deleteFile(String srcFile) throws FileNotFoundException, IOException {

new File(srcFile).delete();

}

/**

* Delete all files in srcFile,This is too difficult for me

* @param srcFile

* @throws FileNotFoundException

* @throws IOException

*/

public static void deleteFiles(String srcFile) throws FileNotFoundException, IOException {

LinkedList<File> dirs = new LinkedList<File>();

dirs.add(new File(srcFile));

while(dirs.size() > 0){

File currentDir = (File)dirs.getFirst();

File[] files = currentDir.listFiles();

boolean emptyDir = true;

for(int i = 0 ;i < files.length;i++) {

if (files[i].isFile()) {

files[i].delete();

} else {

dirs.addFirst(files[i]);

emptyDir = false;

}

}

if (emptyDir){

currentDir.delete();

dirs.removeFirst();

}

}

}

/**

* move srcFile to desFile

* @param srcFile

* @param desFile

* @throws FileNotFoundException

*/

public static void moveFile(String srcFile, String desFile) throws FileNotFoundException, IOException {

copyFile(srcFile, desFile);

new File(srcFile).delete();

}

/**

* move srcFile to desFile

* @param srcFile

* @param desFile

* @throws FileNotFoundException

*/

public static void moveFiles(String srcFile, String desFile) throws FileNotFoundException, IOException {

copyFiles(srcFile, desFile);

deleteFiles(srcFile);

}

/**

* compress files

* @param srcFile

* @param rarFile

* @throws FileNotFoundException

* @throws IOException

*/

public static void compressFile(String _unZipFile, String _zipFile) throws FileNotFoundException, IOException {

File srcFile = new File(_unZipFile);

File zipFile = new File(_zipFile);

DataInputStream dis = new DataInputStream(new FileInputStream(srcFile));

if(!zipFile.exists()) {

File zipdir = new File(zipFile.getParent());

if(!zipdir.exists()) {

zipdir.mkdirs();

}

zipFile.createNewFile();

}

ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(zipFile));

zos.setMethod(ZipOutputStream.DEFLATED);

ZipEntry ze = new ZipEntry(srcFile.getName());

zos.putNextEntry(ze);

DataOutputStream dos = new DataOutputStream(zos);

byte[] buf = new byte[2048];

int len=0;

while((len=dis.read(buf)) != -1) {

dos.write(buf, 0, len);

}

dos.close();

dis.close();

}

/**

* uncompress files

* @param rarFile

* @param srcFile

* @throws FileNotFoundException

* @throws IOException

*/

@SuppressWarnings("unchecked")

public static void unCompressFile(String _zipFile, String _unZipDir) throws FileNotFoundException, IOException {

File unZipFile = new File("_unZipFile");

if(! unZipFile.exists()) {

unZipFile.mkdirs();

}

ZipEntry ze = null;

ZipFile zf = new ZipFile(new File(_zipFile));

Enumeration<ZipEntry> en = (Enumeration<ZipEntry>)zf.entries();

if(en.hasMoreElements()) {

ze = (ZipEntry)en.nextElement();

}

unZipFile = new File(_unZipDir+File.separator+ze.getName());

if(! unZipFile.exists()) {

unZipFile.createNewFile();

}

DataInputStream dis = new DataInputStream(zf.getInputStream(ze));

DataOutputStream dos = new DataOutputStream(new FileOutputStream(unZipFile));

int len = 0;

byte[] buf = new byte[2048];

while((len=dis.read(buf)) != -1) {

dos.write(buf, 0, len);

}

dos.close();

dis.close();

}

/**

*

* @param args

*/

public static void main(String[] args) throws FileNotFoundException, IOException {

//          ArrayList<File> lsFiles = listAllFiles("D:/temp");

//          for(int i=0; i<lsFiles.size(); i++) {

//              System.out.println(lsFiles.get(i).getPath());

//          }

//          System.out.println(lsFiles.size());

//          //copyFile("D:/temp/我的桌面.jpg","D:/temp/test.jpg");

//          try {

//              copyFiles("D:/temp","D:/tt");

//          } catch (IOException e) {

//              // TODO Auto-generated catch block

//              e.printStackTrace();

//          }

//          //moveFile("D:/temp/我的桌面.jpg","D:/temp/test.jpg");

//moveFiles("D:/ttt","D:/temp");

//          File f = new File("D:/temp/软件0820   9308036    .王颜涛.doc");

//          System.out.println(f.getName());

//      try {

//          splitFile("D:/temp/tttt.rar", "D:/temp/test", 3);

//      } catch (IOException e) {

//          e.printStackTrace();

//      }

//      File[] f = {new File("D:/temp/test/tttt1.rar"), new File("D:/temp/test/tttt2.rar"), new File("D:/temp/test/tttt3.rar")};

//      try {

//          mergeFile(f, "D:/temp/test.rar");

//      } catch (IOException e) {

//          // TODO Auto-generated catch block

//          e.printStackTrace();

//      }

//deleteFiles("D:/temp/tttt");

compressFile("D:/temp/bb.pdf","D:/temp/bb.rar");

//unCompressFile("D:/temp/test.rar","D:/temp/test2");

}

}

===按行读取文件内容

File file =new File("D:\Development\weblogic\user_projects\domains\cffg_domain\autodeploy\cffg_p2p\applicationPrint\fxRepayDetail.html");
  StringBuffer tempStr=new StringBuffer();
  String str=null;
  try {
   BufferedReader br=new BufferedReader(new FileReader(file));
   while((str=br.readLine())!=null){
    tempStr.append(str);
   }
   br.close();
  } catch (Exception e) {
   log.error("获取原始模板错误!",e);
  }
  return tempStr.toString();

//获取项目部署路径

private String getMainPath(){
  File f=new File(getClass().getClassLoader().getResource("/").getPath());
  StringBuffer sb=new StringBuffer(f.getParentFile().getParent());
  sb.append(File.separator);
  return sb.toString();
 }

java——操作文件的更多相关文章

  1. Java操作文件夹的工具类

    Java操作文件夹的工具类 import java.io.File; public class DeleteDirectory { /** * 删除单个文件 * @param fileName 要删除 ...

  2. java操作文件的创建、删除、遍历

    java操作文件的创建.删除.遍历: package test; import java.io.File; import java.io.IOException; import java.util.A ...

  3. Java操作文件

    import java.io.File; import java.io.IOException; import java.nio.file.*; import java.nio.file.attrib ...

  4. Java操作文件Util

    package io.guangsoft.utils; import java.io.File; import java.io.FileInputStream; import java.io.File ...

  5. java操作文件常用的 IO流对象

    1.描述:流是字节数据或字符数据序列.Java采用输入流对象和输出流对象来支持程序对数据的输入和输出.输入流对象提供了数据从源点流向程序的管道,程序可以从输入流对象读取数据:输出流对象提供了数据从程序 ...

  6. Java操作文件那点事

    刚开始学Java时候,一直搞不懂Java里面的io关系,在网上找了很多大多都是给个结构图草草描述也看的不是很懂.而且没有结合到java7 的最新技术,所以自己结合API来整理一下,有错的话请指正,也希 ...

  7. Java操作文件转码

    package downloadTest; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.F ...

  8. java操作文件流对象

    所有流对象 InputStream 字节流         FileInputStream 字节流 专门读写非文本文件的         BufferedInputStream 高效流 OutPutS ...

  9. Java删除文件夹和文件

    转载自:http://blog.163.com/wu_huiqiang@126/blog/static/3718162320091022103144516/ 以前在javaeye看到过关于Java操作 ...

随机推荐

  1. 使用Node.js和Redis实现push服务--转载

    出处:http://blog.csdn.net/unityoxb/article/details/8532028 push服务是一项很有用处的技术,它能改善交互,提升用户体验.要实现这项服务通常有两种 ...

  2. Word快捷键

    ▲Word快捷键 [F1]键:帮助 [F2]键:移动文字或图形,按回车键确认 [F4]键:重复上一次的操作 [F5]键:编辑时的定位 [F6]键:在文档和任务窗格或其他Word窗格之间切换 [F8]键 ...

  3. Protocol Buffer基本介绍

    转自:http://www.cnblogs.com/stephen-liu74/archive/2013/01/02/2841485.html 该系列Blog的内容主体主要源自于Protocol Bu ...

  4. select case when

    SELECT CASE WHEN dc.defect_code_name IS NOT NULL THEN dc.defect_code_name WHEN sf.second_defect_leve ...

  5. 【Spring-AOP-学习笔记-7】@Around增强处理简单示例

    阅读目录 简单介绍 章节1:项目结构 章节2:定义切面类.连接点注解类 章节3:为待增强的方法--添加注解声明 章节4:AspectJ配置文件 章节5:测试类xxx 章节6:测试结果 Around 增 ...

  6. bzoj4229: 选择

    Description 现在,我想知道自己是否还有选择. 给定n个点m条边的无向图以及顺序发生的q个事件. 每个事件都属于下面两种之一: 1.删除某一条图上仍存在的边 2.询问是否存在两条边不相交的路 ...

  7. php 获取中文的拼音

    注意事项: 无法识别的中文 亳:bo,如果有此字,结果为空,调用此类之前需要手动加判断 蚌:bang,beng,多音字 莞:guan 圳:zhen 儋:dan 漯:luo 濮:pu 泸:lu 衢:qu ...

  8. 战胜忧虑<2>——忙碌可以消除忧虑

    忙碌可以消除忧虑 当你的脑筋空出来时,也会有东西进去补充,是什么呢?通常都是你的感觉.为什么?因为忧虑.恐惧.憎恨.嫉妒.和羡慕等等情绪,都是由我们的思想所控制的,这种情绪都非常猛烈.会把我们思想中所 ...

  9. [DHTML]什么是DHTML?

    DHTML 将 HTML.JavaScript.DOM 以及 CSS 组合在一起,用于创造动态性更强的网页. DHTML 总结 DHTML 只是一个术语,它描述了 HTML.JavaScript.DO ...

  10. ADF_ADF Faces系列2_使用JSF开发基于Ajax的用户界面:ADF Faces富客户端组件简介(Part2)

    2013-05-01 Created By BaoXinjian