• 文件乱码

    服务器地址

  • 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;

  

最新文章

  1. 《The Linux Command Line》 读书笔记02 关于命令的命令
  2. php读取出字符串中的img标签中的图片路径
  3. [原创]java WEB学习笔记63:Struts2学习之路--表单标签 用户注册模块
  4. Android 模仿电视机关闭界面
  5. Volatile 说明
  6. 如何:在 Winform 动态启动、控制台命令行?
  7. bash if 表达式
  8. ASP 验证、查询AD域账户信息
  9. 基类中定义的虚函数在派生类中重新定义时,其函数原型,包括返回类型、函数名、参数个数、参数类型及参数的先后顺序,都必须与基类中的原型完全相同 but------&gt; 可以返回派生类对象的引用或指针
  10. cf D. Pair of Numbers
  11. Codeforces 286E
  12. Latex 公式在线可视化编辑器
  13. void main(), int main() 和int main(void)的区别
  14. Python中if __name__ == &quot;__main__&quot;: 的理解
  15. 大数据项目之_15_电信客服分析平台_01&amp;02_项目背景+项目架构+项目实现+数据生产+数据采集/消费(存储)
  16. mysql学习1
  17. rem 自适应、整体缩放
  18. URL地址编码和解码
  19. 27、 jq 拖拽
  20. Linux之vmware安装

热门文章

  1. leetcode:Pascal&#39;s Triangle II【Python版】
  2. stardog graphql 简单操作
  3. MFC 对话框Picture Control(图片控件)中静态和动态显示Bmp图片
  4. 万年历(hao123)代码
  5. 理解git
  6. java面试笔试题收集
  7. Nginx隐藏主机信息,proxy_hide_header 与fastcgi_hide_header
  8. bzoj1853幸运数字
  9. 转 WCF中同步和异步通讯总结
  10. npm使用入门(package.json)