文件读写操作-Java
2016-03-11 15:17
555 查看
读文件
字符串读取
File file = new File("/path/test.txt"); BufferedReader bufferedReader = new BufferedReader(new FileReader(file)); String tempString = null; while ((tempString = bufferedReader.readLine()) != null) { //todo:读写 } bufferedReader.close();//关闭 //InputStream in = new GZIPInputStream(new FileInputStream(fileName));读取压缩文件
压缩文件读取
/** * @param fromFilePath 文件路径 * @return * @throws Exception */ public static void segFile(String fromFilePath) throws Exception { InputStream in = new GZIPInputStream(new FileInputStream(fromFilePath)); BufferedReader br = new BufferedReader(new InputStreamReader(in)); String temp = null; while ((temp = br.readLine()) != null) { System.out.println(temp); } in.close(); br.close(); }
写文件
字符串写入
File file = new File("/path/test.txt"); FileOutputStream out = new FileOutputStream(file); BufferedWriter br=new BufferedWriter(new OutputStreamWriter(out)); br.write("test write"); br.flush(); //刷缓存写到文件 br.colse(); //关闭连接
自动获取文件编码
/** * 获取文件编码,其中ansi编码在windows debug模式下不支持 * @param fileName * @return */ public static String getFileEncode(String fileName) { String charSet = ""; try { FileInputStream fis = new FileInputStream(new File(fileName)); byte[] bf = new byte[3]; fis.read(bf); fis.close(); if (bf[0] == -17 && bf[1] == -69 && bf[2] == -65) { charSet = "UTF-8"; } else if ((bf[0] == -1 && bf[1] == -2)) { charSet = "Unicode"; } else if ((bf[0] == -2 && bf[1] == -1)) { charSet = "Unicode big endian"; } else { charSet = "ANSI"; } } catch (Exception e) { e.printStackTrace(); } return charSet; }
相关文章推荐
- 第一个java程序和命令行
- Java IO——Socket:通过多线程实现多客户端与一个服务端通信
- Java IO——Socket:通过多线程实现多客户端与一个服务端通信
- Eclipse项目分包管理
- java.util.zip压缩打包文件总结一:压缩文件及文件下面的文件夹
- java实战之解析xml
- 拦截器—Spring MVC
- java,包装类
- 【转】方便好使的java.util.Properties类
- Install properties Editor for eclipse
- eclipse中project Explorer下项目字体修改
- JAVA8 十大新特性详解
- 给Eclipse提速的7个技巧
- java初始化知识总结
- Java计算TF-IDF值
- Eclipse中修改SVN用户名和密码方法
- spring 定时任务的 执行时间设置规则
- spring mvc 提交表单实现文件上传服务器
- java多线程问题总结
- java自学(第一周)