File 操作

时间:2023-03-09 19:46:22
File 操作
  • 文件乱码

    服务器地址

  • try-with-resource
  • 属性文件获取
  • 文件排序
  • 文件过滤
  • 文件下载
  • 流文件传递

文件乱码:

WINDOWS系统桌面默认使用GBK,Linux系统默认使用UTF-8.

因此linux或者windows的文件名会在对应的上面乱码。

获取路径

因windows的文件路径用 \\ 表示,但也支持 / ,而linux下为/,因此尽量使用/来表示路径, 同时File文件的话,尽量使用 Files.separator.

Test.class.getResources("/") 在window下可以,在linux下会取得null, 应该使用 Test.class.getResources(".")形式在linux下可以,windows下报错,同时如果被打成jar包,也会取得为null 推荐: Test.class.getResources("")

文件名乱码

zipEntry使用时在windows环境下encoding为 gbk,或者gb2312.而在linux系统下为utf-8。Unix英文系统为ISO-8859-1。 new file的时候 文件名也要主要编码new String(fileName.getBytes("charset"), "UTF-8"), 而如果将linux下的文件下载到windows下,文件编码就要用gbk new String(fileName.getBytes(), "gbk")。 文件名可以用ISO-8859-1 new String(fileName.getBytes("ISO-8859-1");

判断系统

logger.debug("--sysEncode--" + System.getProperty("sun.jnu.encoding")); //操作系统编码logger.debug("--fileEncode--" + System.getProperty("file.encoding")); // 程序系统编码 String sysName = system.getParameter("os.name"); sysName.toLowercase.firstStart("win")

服务器地址:

System.getProperty("catalina.home");

属性文件获取:

public static String getValueFromProperties(String key, String filePath){
  Properties pro = new Properties();
  String value = "";
  try {
    pro.load(MyFileUtils.class.getClassLoader().getResourceAsStream(filePath));
    value = pro.getProperty(key);
  } catch (IOException e) {
    logger.error("error is occurs...", e);
  }
  return value;
}

try-with-resource:

java7新推出自动关闭的处理,对于传统的输入流和输出流在关闭时会遇到可能抛出的异常。

        InputStream is = null;
        try {
            is= new FileInputStream("");            *****
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } finally {
            if(is != null) {
                is.close();
            }
        }主动抛出 IOException异常!

使用try-with-resource:

try(InputStream is2= new FileInputStream("")){
        ***
}

文件排序

     /**
      * 对文件列表进行排序
      * @param files
      * @param typeName
      */
     @SuppressWarnings({ "unchecked", "rawtypes" })
     public static List<File> sortFileByType(File[] files, int typeName) {
         List<File> fileList = (List<File>) Arrays.asList(files);

         // 文件排序
         Collections.sort(fileList, new Comparator(){
             @Override
             public int compare(Object o1, Object o2) {
                 File file1 = (File) o1;
                 File file2 = (File) o2;
                 if(file1.isDirectory() || file2.isDirectory()){
                     return 0;
                 }
                 int result = 0;
                 switch(typeName){
                 case TYPE_NAME:
                     result = StringUtils.compareIgnoreCase(file1.getName(), file2.getName()); // 按照文件大小排序
                     break;
                 default :
                     result = 0;
                 }
                 return result;
             }
         });
         return fileList;
     }

文件过滤

     /**
      * 过滤文件
      * @param file
      * @param string
      * @return file[]
      */
     public static File[] filterFileBySuffix(File file, String suffix) {
         // 文件空判断
         File[] fileArray = file.listFiles();
         if(fileArray.length == 0){
             return null;
         }
         /**
          * 过滤文件
          */
         return file.listFiles(new FilenameFilter(){
             @Override
             public boolean accept(File dir, String name) {
                 if(name.endsWith(suffix)){
                     return true;
                 }else{
                     return false;
                 }
             }

         });
     }

文件下载:

  

        boolean result = true;
        InputStream is = null;
        try {
            is = super.getRemoteReqStream(url);
            byte[] data = new byte[1024];
            int length = 0;
            while((length = is.read(data, 0, 1024)) != -1) {
                resp.getOutputStream().write(data, 0, length);
            }
            resp.flushBuffer();
            resp.getOutputStream().close();
        } catch (ClientProtocolException e) {
            result = false;
            logger.error(" request client error...", e);
        } catch (IOException e) {
            result = false;
            logger.error(" request io error...", e);
        } finally {
            if(is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    logger.error("is close error....", e);
                }
            }
        }

  输出流类型设置:

    • Writer osw = new OutputStreamWriter(resp.getOutputStream(), CommonConstants.ENCODE_CHARSET_DEFAULT);
    • ByteArrayOutputStream os = new ByteArrayOutputStream();

  文件下载设置response头信息:

    response.setContentType("application/octet-stream");  //文件流形式

response.setHeader("Content-type","text/html;charset=utf-8");  //设置contentType为text ,字符编码为utf-8

content-type 可用文件后缀名,查找对应的mine-type填入即可。

    response.setContentLength(file.length());                                  //设置文件大小。

    response.addHeader();

response.setCharacterEncoding("utf-8");   //字符集编码

    response.addHeader("Content-Disposition","attachment;filename=FileName.txt");  //设置文件下载,以及文件名

                                          attachment,指示浏览器进行下载

                                          inline会在浏览器中直接打开

    //告诉所有浏览器不要缓存,如果文件固定可以设置缓存

    response.setDateHeader("expires", -1);

    response.setHeader("Cache-control", "no-cache");

    response.setHeader("Pragma", "no-cache");

java 流文件传递

Response response = null;
        try {
            Blob blob = attachDao.downloadAttach(attachId);
            ResponseBuilder responseBuilder = Response.ok(blob.getBinaryStream(),
                    MediaType.APPLICATION_OCTET_STREAM_TYPE);
            responseBuilder.type(MediaType.APPLICATION_OCTET_STREAM_TYPE);            response = responseBuilder.header("content-disposition", "inline;filename=123").build();
        } catch (DbException e) {
            logger.error("blob error..", e);
        } catch(SQLException se) {
            logger.error("sql error..", se);
        }return resonse;