zoukankan      html  css  js  c++  java
  • java-文件和I/O

    理解IO:http://www.importnew.com/23708.html

    一、读写文件:

    FileInputStream

    该流用于从文件读取数据,它的对象可以用关键字 new 来创建。

    有多种构造方法可用来创建对象。

    可以使用字符串类型的文件名来创建一个输入流对象来读取文件:

    InputStream f = new FileInputStream("C:/java/hello");

    也可以使用一个文件对象来创建一个输入流对象来读取文件。我们首先得使用 File() 方法来创建一个文件对象:

    File f = new File("C:/java/hello");
    InputStream out = new FileInputStream(f);

    FileOutputStream

    该类用来创建一个文件并向文件中写数据。

    如果该流在打开文件进行输出前,目标文件不存在,那么该流会创建该文件。

    有两个构造方法可以用来创建 FileOutputStream 对象。

    使用字符串类型的文件名来创建一个输出流对象:

    OutputStream f = new FileOutputStream("C:/java/hello")

    也可以使用一个文件对象来创建一个输出流来写文件。我们首先得使用File()方法来创建一个文件对象:

    File f = new File("C:/java/hello");
    OutputStream f = new FileOutputStream(f);
    import java.io.*;
     
    public class fileStreamTest2{
      public static void main(String[] args) throws IOException {
        
        File f = new File("a.txt");
        // 构建FileOutputStream对象,文件不存在会自动新建
        FileOutputStream fop = new FileOutputStream(f);
        // 构建OutputStreamWriter对象,参数可以指定编码,默认为操作系统默认编码,windows上是gbk
        OutputStreamWriter writer = new OutputStreamWriter(fop, "UTF-8");
        // 写入到缓冲区
        writer.append("中文输入");
        //换行
        writer.append("
    ");
        // 刷新缓存冲,写入到文件,如果下面已经没有写入的内容了,直接close也会写入
        writer.append("English");
        //关闭写入流,同时会把缓冲区内容写入文件,所以上面的注释掉
        writer.close();
        // 关闭输出流,释放系统资源
        fop.close();
     
    
    
        // 构建FileInputStream对象
        FileInputStream fip = new FileInputStream(f);
        // 构建InputStreamReader对象,编码与写入相同
        InputStreamReader reader = new InputStreamReader(fip, "UTF-8");
          // 转成char加到StringBuffer对象中
        StringBuffer sb = new StringBuffer();
        while (reader.ready()) {
          sb.append((char) reader.read());
        }
        System.out.println(sb.toString());
        // 关闭读取流
        reader.close();
        // 关闭输入流,释放系统资源
        fip.close();
     
      }
    }

     写文件:

    String tPath = request.getSession().getServletContext().getRealPath("/");
            FileOutputStream outputStream = null;
            try {
                if (fileType.equals("doc") || fileType.equals("docx")) {
                    String folderPath = tPath.substring(0,tPath.lastIndexOf("\")) + "/uploadfiles/conferencefile/"+topicInfo.getId();
                    tPath = folderPath +"/"+ fileName + "." + fileType;
                    //--------写入文件内容-----------------
                    File folder = new File(folderPath);
                    if(!folder.exists())    
                    {   
                        folder.mkdirs();    
                    }    
                    File file = new File(tPath);
                    if(!file.exists())    
                    {   
                        try {    
                            file.createNewFile();    
                        } catch (IOException e) {  
                            e.printStackTrace();    
                        }    
                    }    
                    outputStream = new FileOutputStream(file);
                    byte[] bytes = Base64.decodeBase64(base64String);
                    outputStream.write(bytes,0,bytes.length);
                    //-----------------------------------
                }
            } catch (Exception e) {
            }
            finally {
                try {
                    outputStream.close();
                } catch (IOException e) {
                    // TODO 自动生成的 catch 块
                    e.printStackTrace();
                }
            }

    二、创建目录:

    判断文件是否存在

    File file = new File(filePath + builder.toString());
            if(!file.exists())    
            {    
                try {    
                    file.createNewFile();    
                } catch (IOException e) {  
                    e.printStackTrace();    
                }    
            }    

    判断文件夹是否存在

    File类中有两个方法可以用来创建文件夹:

    • mkdir( )方法创建一个文件夹,成功则返回true,失败则返回false。失败表明File对象指定的路径已经存在,或者由于整个路径还不存在,该文件夹不能被创建。
    • mkdirs()方法创建一个文件夹和它的所有父文件夹。
    File filePath = new File("D:\Video");
    if (!filePath.exists()) {
         filePath.mkdirs();
    }

    三、读取目录:

    判断是文件夹还是文件

    import java.io.File;
     
    public class DirList {
      public static void main(String args[]) {
        String dirname = "/tmp";
        File f1 = new File(dirname);
        if (f1.isDirectory()) {
          System.out.println( "目录 " + dirname);
          String s[] = f1.list();
          for (int i=0; i < s.length; i++) {
            File f = new File(dirname + "/" + s[i]);
            if (f.isDirectory()) {
              System.out.println(s[i] + " 是一个目录");
            } else {
              System.out.println(s[i] + " 是一个文件");
            }
          }
        } else {
          System.out.println(dirname + " 不是一个目录");
        }
      }
    }

    四、删除目录或文件

    删除文件可以使用 java.io.File.delete() 方法。

    删除文件及目录

    //删除文件及目录
      public static void deleteFolder(File folder) {
        File[] files = folder.listFiles();
            if(files!=null) { 
                for(File f: files) {
                    if(f.isDirectory()) {
                        deleteFolder(f);
                    } else {
                        f.delete();
                    }
                }
            }
            folder.delete();
        }

    五、读写excel文件

    需要jxl.jar jar包支持,jxl.jar好像不支持.xlsx格式excel文件,需要把.xlsx格式的excel文件另存为.xls格式文件

    使用poi读取excel文件,HSSFWorkbook与XSSFWorkbook,前一个可以用来解析以.xls结尾的excel,后一个可以用来解析.xlsx结尾的excel

    poi:

    //读取excel文件内容
                List<User> userExcel = new ArrayList<>();
                File file = null;
                try {
                    file = new File(filePath);
                } catch (Exception e) {
                    responseResult.setMsg("检查文件路径是否正确:"+filePath);
                    return responseResult;
                }
                FileInputStream fStream = new FileInputStream(file);
                XSSFWorkbook xss = new XSSFWorkbook(fStream);
                XSSFSheet sheet = xss.getSheetAt(0);
                for(int i=0;i<sheet.getLastRowNum();i++) {
                    Row row = sheet.getRow(i);
                    User user = new User();
                    for(int j=0;j<row.getLastCellNum();j++) {
                        Cell cell = row.getCell(j, Row.CREATE_NULL_AS_BLANK);
                        switch (cell.getCellType()) {
                        case Cell.CELL_TYPE_BLANK:
                            
                            break;
                        case Cell.CELL_TYPE_BOOLEAN:
                           
                            break;
                        case Cell.CELL_TYPE_NUMERIC:
                            // 数值
                            
                            break;
                        case Cell.CELL_TYPE_STRING:
                            if (i != 0) {
                                String valueStr = cell.getStringCellValue();
                                if (j == 7) {
                                    //登录名
                                    user.setUserLoginNameHY(valueStr);
                                }else if (j == 9) {
                                    //身份证
                                    user.setUserCardEncryptionHY(valueStr);
                                }
                            }
                            break;
                        case Cell.CELL_TYPE_ERROR:
                            
                            break;
                        default:
                            break;
                        }
                    }
                    if (i!=0) {
                        userExcel.add(user);
                    }
                    
                }
    View Code

    jxl:

    public void readExcel(File file) {
            try {  
                //读取excel文件内容
                List<ExcelPollution> listPollution = new ArrayList<>();
                List<ExcelClinic> listClinic = new ArrayList<>();
                // 创建输入流,读取Excel  
                InputStream is = new FileInputStream(file.getAbsolutePath());  
                // jxl提供的Workbook类  
                Workbook wb = Workbook.getWorkbook(is);  
                // Excel的页签数量  
                //int sheet_size = wb.getNumberOfSheets();  
                //for (int index = 0; index < sheet_size; index++)
                {  
                    // 每个页签创建一个Sheet对象  
                    Sheet sheet = wb.getSheet(0);
                    // sheet.getRows()返回该页的总行数  
                    for (int i = 0; i < sheet.getRows(); i++) { 
                        ExcelPollution excelPollution = new ExcelPollution(); 
                        // sheet.getColumns()返回该页的总列数  
                        for (int j = 0; j < sheet.getColumns(); j++) {  
                            String cellinfo = sheet.getCell(j, i).getContents();  
                            if (j == 0) {
                                excelPollution.setLocation(cellinfo);
                            }
                            else if (j == 1) {
                                String dString = cellinfo;
                                if (i > 0) {
                                    dString = "20" + cellinfo.replace("-", "/");
                                }
                                excelPollution.setDate(dString);
                            }
                            else if (j == 2) {
                                excelPollution.setSO2(cellinfo);
                            }
                            else if (j == 3) {
                                excelPollution.setNO2(cellinfo);
                            }
                            else if (j == 4) {
                                excelPollution.setPM10(cellinfo);
                            }
                            else if (j == 5) {
                                excelPollution.setCO(cellinfo);
                            }
                            else if (j == 6) {
                                excelPollution.setO3(cellinfo);
                            }
                            else if (j == 7) {
                                excelPollution.setPM25(cellinfo);
                            } 
                        }  
                        listPollution.add(i, excelPollution);
                    }  
                }  
                
                File file2 = new File("D://Java//DoWork//clinic1.xls");  
                // 创建输入流,读取Excel  
                InputStream is2 = new FileInputStream(file2.getAbsolutePath());  
                // jxl提供的Workbook类  
                Workbook wb2 = Workbook.getWorkbook(is2);  
                // Excel的页签数量  
                //int sheet_size2 = wb2.getNumberOfSheets();  
                //for (int index = 0; index < sheet_size2; index++) 
                {  
                    // 每个页签创建一个Sheet对象  
                    Sheet sheet2 = wb2.getSheet(1);
                    // sheet.getRows()返回该页的总行数  
                    for (int i = 0; i < sheet2.getRows(); i++) { 
                        ExcelClinic excelClinic = new ExcelClinic(); 
                        // sheet.getColumns()返回该页的总列数  
                        for (int j = 0; j < sheet2.getColumns(); j++) {  
                            String cellinfo = sheet2.getCell(j, i).getContents();  
                            if (j == 0) {
                                excelClinic.setStation(cellinfo);
                            }
                            else if (j == 1) {
                                String dString = cellinfo;
                                if (i > 0) {
                                    dString = "20" + cellinfo.replace("-", "/");
                                }
                                excelClinic.setDate(dString);
                            }
                            else if (j == 2) {
                                excelClinic.setSO2(cellinfo);
                            }
                            else if (j == 3) {
                                excelClinic.setNO2(cellinfo);
                            }
                            else if (j == 4) {
                                excelClinic.setPM10(cellinfo);
                            }
                            else if (j == 5) {
                                excelClinic.setCO(cellinfo);
                            }
                            else if (j == 6) {
                                excelClinic.setO3(cellinfo);
                            }
                            else if (j == 7) {
                                excelClinic.setPM25(cellinfo);
                            }
                            else if (j == 8) {
                                excelClinic.setDiagnose(cellinfo);
                            }
                            else if (j == 9) {
                                excelClinic.setICD_10(cellinfo);
                            }
                            else if (j == 10) {
                                String dString = cellinfo;
                                if (i > 0) {
                                    dString = "20" + cellinfo.replace("-", "/");
                                }
                                excelClinic.setDate_birth(dString);
                            }
                            else if (j == 11) {
                                excelClinic.setAge_0(cellinfo);
                            }
                            else if (j == 12) {
                                excelClinic.setGender(cellinfo);
                            }
                            else if (j == 13) {
                                excelClinic.setAge_1(cellinfo);
                            }
                            else if (j == 14) {
                                String dString = "20" + cellinfo.replace("-", "/");
                                excelClinic.setDate_discharge(dString);
                            }
                            else if (j == 15) {
                                excelClinic.setRegisted_address(cellinfo);
                            }
                            else if (j == 16) {
                                excelClinic.setAdmission_cost(cellinfo);
                            }
                            else if (j == 17) {
                                excelClinic.setAddress_present(cellinfo);
                            }
                            else if (j == 18) {
                                excelClinic.setICD(cellinfo);
                            }
                            else if (j == 19) {
                                excelClinic.setID(cellinfo);
                            }
                        }
                        
                        listClinic.add(i, excelClinic);
                    }  
                }  
                
                if (listClinic.size() >0 && listPollution.size() > 0) {
                    for (ExcelClinic clinic : listClinic) {
                        for (ExcelPollution pollution : listPollution) {
                            if (pollution.getLocation().equals(clinic.getStation()) && pollution.getDate().equals(clinic.getDate())) {
                                clinic.setSO2(pollution.getSO2());
                                clinic.setNO2(pollution.getNO2());
                                clinic.setPM10(pollution.getPM10());
                                clinic.setCO(pollution.getCO());
                                clinic.setO3(pollution.getO3());
                                clinic.setPM25(pollution.getPM25());
                                try {
                                    if (pollution.getPM10().equals("PM10") && pollution.getPM25().equals("PM2.5")) {
                                        clinic.setPMc("PMc");
                                    }
                                    else if (!pollution.getPM10().equals("") && !pollution.getPM25().equals("") && pollution.getPM10() != null && pollution.getPM25() != null) {
                                        Integer pMc = Integer.parseInt(clinic.getPM25()) - Integer.parseInt(clinic.getPM10());
                                        clinic.setPMc(pMc.toString());
                                    }
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                                break;
                            }
                        }
                    }
                }
                          
                //按照对象中的date日期进行排序
                Collections.sort(listClinic, new Comparator<ExcelClinic>() {
                    @Override
                    public int compare(ExcelClinic o1, ExcelClinic o2) {
                        SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd");
                        try {
                            Date dt1 = format.parse(o1.getDate());
                            Date dt2 = format.parse(o2.getDate());
                            if (dt1.getTime() > dt2.getTime()) {
                                return 1;
                            } else if (dt1.getTime() < dt2.getTime()) {
                                return -1;
                            } else {
                                return 0;
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        return 0;
                    }
                });
    
                //写入excel文件
                try {  
                    // 打开文件  
                    WritableWorkbook book = Workbook.createWorkbook(new File("D://Java//DoWork//test.xls"));  
                    // 生成名为“sheet1”的工作表,参数0表示这是第一页  
                    WritableSheet sheet = book.createSheet("sheet1", 0);  
                    for (int i = 0; i<listClinic.size();i++) {
                        // 在Label对象的构造子中指名单元格位置是第一列第一行(0,0),单元格内容为string  
                        Label label0 = new Label(0, i, listClinic.get(i).getStation());  
                        // 将定义好的单元格添加到工作表中  
                        sheet.addCell(label0);  
                        Label label1 = new Label(1, i, listClinic.get(i).getDate());  
                        sheet.addCell(label1);  
                        Label label2 = new Label(2, i, listClinic.get(i).getSO2());  
                        sheet.addCell(label2);  
                        Label label3 = new Label(3, i, listClinic.get(i).getNO2());  
                        sheet.addCell(label3);  
                        Label label4 = new Label(4, i, listClinic.get(i).getPM10());  
                        sheet.addCell(label4);  
                        Label label5 = new Label(5, i, listClinic.get(i).getCO());  
                        sheet.addCell(label5);  
                        Label label6 = new Label(6, i, listClinic.get(i).getO3());  
                        sheet.addCell(label6);  
                        Label label7 = new Label(7, i, listClinic.get(i).getPM25());  
                        sheet.addCell(label7);
                        Label label8 = new Label(8, i, listClinic.get(i).getPMc());  
                        sheet.addCell(label8);  
                        Label label9 = new Label(9, i, listClinic.get(i).getDiagnose());  
                        sheet.addCell(label9);  
                        Label label10 = new Label(10, i, listClinic.get(i).getICD_10());  
                        sheet.addCell(label10);  
                        Label label11 = new Label(11, i, listClinic.get(i).getDate_birth());  
                        sheet.addCell(label11);  
                        Label label12 = new Label(12, i, listClinic.get(i).getAge_0());  
                        sheet.addCell(label12);  
                        Label label13 = new Label(13, i, listClinic.get(i).getGender());  
                        sheet.addCell(label13);  
                        Label label14 = new Label(14, i, listClinic.get(i).getAge_1());  
                        sheet.addCell(label14);  
                        Label label15 = new Label(15, i, listClinic.get(i).getDate_discharge());  
                        sheet.addCell(label15);  
                        Label label16 = new Label(16, i, listClinic.get(i).getRegisted_address());  
                        sheet.addCell(label16);  
                        Label label17 = new Label(17, i, listClinic.get(i).getAdmission_cost());  
                        sheet.addCell(label17);  
                        Label label18 = new Label(18, i, listClinic.get(i).getAddress_present());  
                        sheet.addCell(label18);  
                        Label label19 = new Label(19, i, listClinic.get(i).getICD());  
                        sheet.addCell(label19);  
                        Label label20 = new Label(20, i, listClinic.get(i).getID());  
                        sheet.addCell(label20);  
                    }
                    
                    // 写入数据并关闭文件  
                    book.write();  
                    book.close();  
                } catch (Exception e) {  
                    System.out.println(e);  
                }  
            } catch (Exception e) {  
                e.printStackTrace();  
            }        
        }
    View Code

    六、读取文件内容:

    org.apache.commons.codec.binary.Base64
     
    
    String path = tPath.substring(0,tPath.lastIndexOf("\")) + file.getUrl();
    File f = new File(path);
    InputStream iStream = new FileInputStream(f);
    byte[] bytes = new byte[(int)f.length()];//或new byte[iStream.available()]
    iStream.read(bytes);
    String content = new String(Base64.encodeBase64(bytes),"utf-8");
    iStream.close();
    //------------------------------------------------------------------------------


    InputStream inputStream = new BufferedInputStream(new FileInputStream(file)); InputStreamReader iReader = new InputStreamReader(inputStream); char len; while (iReader.ready()) { len = (char) iReader.read(); String string2 = String.valueOf(len); ss += string2; } inputStream.close(); iReader.close();

     问题:

    1、代码调试正常,发布war包在tomcat运行,读取html页面内容出现乱码:

    原因:读取的时候,编码没有设置(修改为UTF-8读取)

    例:

    OutputStreamWriter bw = null;
    FileOutputStream fop = null;
    BufferedReader br =null;
    InputStreamReader isr=null;
    FileInputStream fis=null;
    
    File file = new File(filename);
    fop = new FileOutputStream(file);
    bw = new OutputStreamWriter(fop, "UTF-8");
    ..... File fileR
    = new File(fromPath); fis = new FileInputStream(fileR); isr = new InputStreamReader(fis, "UTF-8"); br = new BufferedReader(isr); String tempStr; String len=""; while((tempStr = br.readLine()) != null)
    {
      len += tempStr;
    }

      // 关闭输入流,释放系统资源
      iStream.close();
      iReader.close();
      br.close();

     效率较高:

    InputStream inputStream = null;
    BufferedInputStream input = null;
    ByteArrayOutputStream outputStream  = null;
    try {
        inputStream = ftpClient.retrieveFileStream(fileName);
        input = new BufferedInputStream(inputStream);
        outputStream = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len = -1;
        while ((len=input.read(buffer))!=-1){
              outputStream.write(buffer,0,len);
        }
    xmlStr = new String( outputStream.toByteArray(),"GBK");
    }
    bufferedInputStream = new BufferedInputStream(inputStream);
    byte[] bytes = new byte[inputStream.available()];
    bufferedInputStream.read(bytes);
    xmlStr = new String(bytes,"GBK");
    int len;
    while ((len = bInputStream.read(bytes)) != -1){
              outputStream.write(bytes,0,len);
    }
    BASE64Encoder encoder = new BASE64Encoder();
    String base64Str = encoder.encode(outputStream.toByteArray());

     效率较低:

    String len;
    while ((len = bufferedReader.readLine()) != null){
           xmlStr += len;
    }
  • 相关阅读:
    关于js原型链继承的一些复习
    echarts 柱状图
    js的属性监听
    改变input[type=range]的样式 动态滑动
    占位符 css
    JS简单实现:根据奖品权重计算中奖概率实现抽奖的方法
    layui navTree 动态渲染菜单组件介绍
    配置单机Kafka
    树莓派安装pip3以及扩展包的方法
    Gunicorn+Nginx+Flask项目部署
  • 原文地址:https://www.cnblogs.com/lijianda/p/8744656.html
Copyright © 2011-2022 走看看