Java文件读写(IO)常用代码

     /**
     * 创建一个新的文件
     * @param relativePath 相对路径
     * @param fileName 文件名
     * @return
     * @throws IOException
     */
    public File createFile(String relativePath, String fileName) throws IOException {

        String upPath = getFileUploadPath() + relativePath + "//";
        System.out.println("upPath:" + upPath);/
        System.out.println("fileName:" + fileName);/
        String nameWithoutExt = getNameWithoutExtension(fileName);
        String ext = getExtension(fileName);

        createDirectory(upPath);// 上传目录不存在则创建目录
        File newFile = new File(upPath + fileName);

        // 若有重名文件则修改名称创建新的文件
        for (int counter = 1; newFile.exists(); counter ++) {
            fileName = nameWithoutExt + "(" + String.valueOf(counter) + ")." + ext;
            newFile = new File(upPath + fileName);
        }
        newFile.createNewFile();
        return newFile;
    }

=================================================================================

 

    /**
    * 文件的写入 (单行写入)
    * @param filePath(文件路径)
    * @param fileName(文件名)
    * @param args
    * @throws IOException
    */
    public void writeFile(String filePath,String fileName,String args) throws IOException
    {
    FileWriter fw = new FileWriter(filePath+fileName);
    fw.write(args);
    fw.close();
    }

=================================================================================

 

    /**
     * 文件读写
     *
     * @author 贺圆波
     * 2009-10-26
     * @param fileName
     * @return void
     */
    public void addLogger(String fileName) {
        String line = "";
        File file = new File("E://tkmFile//knlgfile//template//template.txt");
        BufferedReader reader = null;
        try {
            reader = new BufferedReader(new FileReader(file));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        try {
            while (reader.read() != -1) {   
                line += reader.readLine();
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (reader != null) {
                    reader.close();
                    reader = null;
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        line = " " + line.substring(0, line.lastIndexOf("]"));
        line += ",[/"750/", /"" + fileName + "/", /"" + fileName + "/"]" + "];";
//        System.out.println(line);
        FileWriter fw = null;
        try {
            fw = new FileWriter(Constants.templatePath);
            fw.write(line);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (fw != null) {
                    fw.close();
                    fw = null;
                }
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
    }

=================================================================================

 

====================================================================================

    /**
    * 文件的写入(按数组逐行写入)
    * @param filePath(文件路径)
    * @param fileName(文件名)
    * @param args[]
    * @throws IOException
    */
    public void writeFile(String filePath,String fileName,String[] args) throws IOException
    {
    FileWriter fw = new FileWriter(filePath+fileName);
    PrintWriter out=new PrintWriter(fw);
    for(int i=0;i<args.length;i++)
    {
    out.write(args[i]);
    out.println();
    out.flush();
    }
    fw.close();
    out.close();
    }

===================================================================================

    /**
     * 生成Excel文件发送给用户
     * @author he 2009-10-20
     * @param response - HttpervletResponse 对象
     * @param sheetName - 表名
     * @param titles - 标题数组
     * @param contents - 内容集合,包含多个内容的String数组
     * @throws Exception
     */
    public static void writeExcel(HttpServletResponse response, String sheetName, String titles[], List contents,String filename) throws Exception {
       
        response.setHeader("Content-disposition","attachment; filename="+filename+".xls");
        response.setContentType("application/msexcel");
       
        OutputStream os= response.getOutputStream();
        WritableWorkbook wBook=Workbook.createWorkbook(os);
       
        WritableSheet sheet=wBook.createSheet(sheetName, 0);
       
         //设置字体
        WritableFont font = new WritableFont(WritableFont.ARIAL,10,WritableFont.BOLD,false,UnderlineStyle.NO_UNDERLINE,Colour.BLACK);
        WritableCellFormat cFormat = new WritableCellFormat(font);
        cFormat.setWrap(false);
        cFormat.setAlignment(Alignment.CENTRE);
       
         //设置背景色
        cFormat.setBackground(Colour.LIGHT_ORANGE);
        cFormat.setWrap(true);
        sheet.getSettings().setDefaultColumnWidth(12);
       
       
        //表头
        for(int i=0;i<titles.length;i++){
            sheet.addCell(new Label(i,0,titles[i],cFormat));
        }
        for(int i = 0; i < contents.size(); i++){
            String[] content = (String[]) contents.get(i);
            for (int j = 0; j < content.length; j++) {
                sheet.addCell(new Label(j, i+1, content[j] == null ? " " : content[j]));
            }
        }
        wBook.write();
        wBook.close();
        os.close();
    }

==========================================================================

     /**
      * 解压缩
      * @author he
      * 2009-10-19
      * @param fileAllPath 文件全路径名
     * @throws IOException
      */
     public static void unZip(String fileAllPath) throws IOException{
         int index=-1;
         if(fileAllPath.lastIndexOf("/")>=0){
             index=fileAllPath.lastIndexOf("/");
         }else{
             index=fileAllPath.lastIndexOf("//");
         }
         String filePath=fileAllPath.substring(0,index+1);
         
         ZipFile zipFile = new ZipFile(fileAllPath);
         Enumeration emu = zipFile.entries();
         int i=0;
         while(emu.hasMoreElements()){
             ZipEntry entry = (ZipEntry)emu.nextElement();
             //会把目录作为一个file读出一次,所以只建立目录就可以,之下的文件还会被迭代到。
             if (entry.isDirectory())
             {
                 new File(filePath + entry.getName()).mkdirs();
                 continue;
             }
             BufferedInputStream bis = new BufferedInputStream(zipFile.getInputStream(entry));
             File file = new File(filePath + entry.getName());
             //加入这个的原因是zipfile读取文件是随机读取的,这就造成可能先读取一个文件
             //而这个文件所在的目录还没有出现过,所以要建出目录来。
             File parent = file.getParentFile();
             if(parent != null && (!parent.exists())){
                 parent.mkdirs();
             }
             FileOutputStream fos = new FileOutputStream(file);
             BufferedOutputStream bos = new BufferedOutputStream(fos,BUFFER);          
            
             int count;
             byte data[] = new byte[BUFFER];
             while ((count = bis.read(data, 0, BUFFER)) != -1)
             {
                 bos.write(data, 0, count);
             }
             bos.flush();
             bos.close();
             bis.close();
         }
         zipFile.close();
     }

=============================================================================】

=============================================================================】

package test;

import java.io.*;

 

// 文件读写
public class FileStreamDemo {

    public static void main(String[] args) {

        try {
            byte[] buffer = new byte[1024];

            // 来源文件
            FileInputStream fileInputStream =
                new FileInputStream(new File("D://FileStreamDemo1.txt"));

            // 目的文件
            FileOutputStream fileOutputStream =
                new FileOutputStream(new File("D://FileStreamDemo2.txt"));

 

//构建方法的第二个append参数如果设置为true,在开启流时如果文件不存在则会新建一个文件,如果文件存在就直接开启流,并将写入的数据附加至//文件末端。
//          FileOutputStream fileOutputStream =
//              new FileOutputStream(new File("D://FileStreamDemo2.txt"), true);
            // available()可取得未读取的数据长度
            System.out.println("复制文件:" +
                    fileInputStream.available() + "字节");

            while(true) {
                if(fileInputStream.available() < 1024) {
                    // 剩余的数据比1024字节少
                    // 一位一位读出再写入目的文件
                    int remain = -1;
                    while((remain = fileInputStream.read()) != -1) {
                        System.out.println(remain);
                        fileOutputStream.write(remain);
                    }
                    break;
                } else {
                    // 从来源文件读取数据至缓冲区
                    fileInputStream.read(buffer);
                    // 将数组数据写入目的文件
                    fileOutputStream.write(buffer);
                }
            }
            // 关闭流
            fileInputStream.close();
            fileOutputStream.close();
            System.out.println("复制完成");
        } catch(ArrayIndexOutOfBoundsException e) {
            System.out.println("using: java FileStreamDemo src des");
            e.printStackTrace();
        } catch(IOException e) {
            e.printStackTrace();
        }
    }

}

=============================================================================】

=============================================================================】

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值