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;
File 操作的更多相关文章
- Java文件File操作一:文件的创建和删除
一.简述 File 文件类,主要对文件进行相关操作.常用的File操作有:文件(夹)的创建.文件(夹)的删除,文件的读入和下载(复制)等: 二.文件(夹)的创建和删除 1.创建过程 实例: //cre ...
- python学习笔记3---浅拷贝和深拷贝,file操作
import copy a=[1,2,3,['a','b']] b=a c= copy.copy(a)---浅拷贝 d=copy.deepcopy(a)---深拷贝 file操作: python 文件 ...
- 【转载】Java File操作汇总
转载自博客:https://passport.cnblogs.com/user/signin?ReturnUrl=https%3A%2F%2Fwww.cnblogs.com%2F 本文通过大量的示例, ...
- phonegap file操作
phonegap中,有时候需要操作到手机中的文件,这个时候就需要用到phonegap官方提供的插件 file ,英文好的可以直接参考官方文档 首先是安装插件:(需要phonegap 3.0 以上,不止 ...
- [Python Study Notes] Basic I\O + File 操作
列表操作 Python 文件I/O 本章只讲述所有基本的的I/O函数,更多函数请参考Python标准文档. 打印到屏幕 最简单的输出方法是用print语句,你可以给它传递零个或多个用逗号隔开的表达式. ...
- Java-IO流之File操作和Properties操作
java的File类主要是用来操作文件的元数据,稍作演示如下: 其中方法getAllJavaFile()是使用了过滤器FileFileter,这个过滤器只需要实现accept方法,判断什么样的文件返回 ...
- Java 学习笔记 IO流与File操作
可能你只想简单的使用,暂时不想了解太多的知识,那么请看这里,了解一下如何读文件,写文件 读文件示例代码 File file = new File("D:\\test\\t.txt" ...
- File操作
对文件进行操作(只操作小文件) bool Exists(string path) 判断文件是否存在 FileStream Create(string path) 创建文件 void Move(stri ...
- C#常用操作类库四(File操作类)
public class FileHelper : IDisposable { private bool _alreadyDispose = false; #region 构造函数 public Fi ...
- c# File 操作
//1.---------文件夹创建.移动.删除--------- //创建文件夹 Directory.CreateDirectory(Server.MapPath("a")); ...
随机推荐
- docker 方式运行drill
drill 1.14 版本已经官方支持使用docker 直接运行可,还是比较方便的,尽管镜像 有点大,但是实际测试使用还是比较方便的,实际上自己做一个也比较简单. 下载镜像 docker pull d ...
- 在Win7下新建库并修改图标
win7中在库中添加桌面方法详解 1.在空白处,鼠标右键选择新建——库. 2.命名为桌面,然后选择桌面. 3.鼠标右键选择属性. 4.点击包括文件夹. 5.选择桌面,点击包括文件夹按钮. 6.点击确定 ...
- Centos7 通过SSH使用密钥实现免密登录
Public Key认证的主要魅力在于认证时承诺不必提供密码就能够同远程系统建立连接. Public Key认证的基础在于一对密钥,public key和private key,public key对 ...
- 使用OPRT库来实现局域网视频实时传输
转载,侵删 4.代码设计 目的:使用OPRT库来实现局域网视频实时传输 参考samle_venc.c进行ortp开发 4.1.程序流程如下 step1:定义变量,VPSS,VENC,零散变量 step ...
- java 设计模式:单例模式
Java中单例模式是一种常见的设计模式,单例模式的写法有好几种,这里主要介绍三种:懒汉式单例.饿汉式单例.登记式单例. 单例模式有以下特点: 1.单例类只能有一个实例. 2.单例类必须自己创建自己的唯 ...
- C/C++基础----表达式
1 基本概念 类型转换,小整型通常会被提升. 运算符重载,运算对象的个数.运算符的优先级和结合律都是无法改变的. 左值右值,对象被用做右值时,使用的是对象的值(内容):用做左值时,使用的是对象的身份( ...
- 【整理总结】代码沉淀 - CefSharp - 比较流行的第三方内嵌浏览器组件
.NET (WPF and Windows Forms) bindings for the Chromium Embedded Framework web: https://github.com/ce ...
- Monit安装与配置
Monit安装与配置 monit 监控并自动重启服务 官方文档
- Centos 6.5 升级python到版本2.7.12
查看python版本: python --version 1.下载Python-2.7.12 wget https://www.python.org/ftp/python/2.7.12/Python- ...
- configure: error: You need a C++ compiler for C++ support.
安装pcre包的时候提示缺少c++编译器 报错信息如下: configure: error: You need a C++ compiler for C++ support. 解决办法,使用yum安装 ...