Java--读写文件综合
2016-01-20 19:29
686 查看
package javatest; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.FileReader; import java.text.SimpleDateFormat; import java.util.Date; class fileTest { public static void main(String[] args) { Date dt = new Date(); SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss"); String s = df.format(dt); System.out.println(s); String path = "C:\\Users\\hp\\Desktop\\test.txt"; //readFile(path); /*writeTxtFile("C:\\Users\\hp\\Desktop\\test2.txt.", "C:\\Users\\hp\\Desktop\\test.txt");*/ writeBinaryFile("C:\\Users\\hp\\Desktop\\c.jpg.", "C:\\Users\\hp\\Desktop\\a.jpg"); } //读取文本文件 public static void readFile(String filePath) { File file = new File(filePath); if (!file.exists()) { System.out.println("No such file"); } else { try { BufferedReader reader = new BufferedReader(new FileReader(file)); String line = ""; // StringBuffer sb=new StringBuffer(); while ((line = reader.readLine()) != null) { System.out.println(line); // sb.append(line); } reader.close(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } } //复制文本文件 public static void writeTxtFile(String destFile, String srcFile) { try { File file = new File(destFile); if (!file.exists()) { System.out.println("No such file"); file.createNewFile(); } else { BufferedReader reader = new BufferedReader(new FileReader( new File(srcFile))); String line = null; FileOutputStream out = new FileOutputStream(file); while ((line = reader.readLine()) != null) { out.write(line.getBytes()); } System.out.println("Copyed"); out.close(); reader.close(); } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } //复制二进制文件,如图片等 public static void writeBinaryFile(String destFile, String srcFile){ try { File file = new File(destFile); if (file.exists()) { System.out.println("File already exists,stop writting!"); } else { System.out.println("Creating new file..."); file.createNewFile(); FileInputStream fin = new FileInputStream(new File(srcFile)); byte[]buff=new byte[2014]; FileOutputStream fout = new FileOutputStream(file); while((fin.read(buff))!= -1) { fout.write(buff); } System.out.println("Copyed"); fout.close(); fin.close(); } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
相关文章推荐
- Eclipse下把jar包放到工程lib下和通过buildpath加载有什么不同(解决找不到类的中级方法)
- java定时器的使用(Timer)
- Java--时间处理
- 【慕课笔记】第三章 常用的运算符 第6节 JAVA中的条件运算符
- 【maven基础】Eclipse中Maven安装与配置
- SpringMvc (六) 自定义验证
- JavaSE入门学习5:Java基础语法(一)
- 提高Eclipse对编辑jsp文件的智能提示-安装Aptana Studio 3插件
- Mybatis整合Spring
- Spring的BeanUtils.copyProperties用法
- [Java工具类]spring常用工具类 2.特殊字符转义和方法入参检测工具类
- [Java工具类]Spring常用工具类 1.文件资源操作和Web相关工具类
- java.lang.NoSuchFieldException: resourceEntries
- Java 基础——类和对象
- Java String.isEmpty()
- SpringMVC token 防止表单重复提交
- 分析和解决JAVA 内存泄露的实战例子
- Java的内存泄漏
- Windows 测试txt或者java文件传递到Mac上出现乱码
- 将MyEclipse的配色方案还原到最初的状态(主题还原)