Java--读写文件综合
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(); } } }