import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; public class TestClass { public static void main(String[] args) { readFile(); writeFile(); copyFile(); deleteFile(); } public static void readFile() { try { String _line; FileReader _file = new FileReader("D:\\TestFile.txt"); BufferedReader _buffer = new BufferedReader(_file); while ((_line = _buffer.readLine()) != null) { System.out.println(_line); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } public static void writeFile() { File file = new File("D:\\NewTestFile.txt"); FileWriter fw = null; try { fw = new FileWriter(file); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } BufferedWriter bw = new BufferedWriter(fw); try { bw.write("Decoderr:Java Blog"); bw.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println("Done"); } public static void deleteFile() { File file = new File("D:\\NewTestFile.txt"); boolean success = file.delete(); if (success) { System.out.println("File " + file.getName() + " is deleted"); } else { System.out.println("Can not delete file " + file.getName()); } } public static void copyFile() { FileInputStream inputStream = null; FileOutputStream outputStream = null; try { File oldFile = new File("D:\\TestFile.txt"); File newFile = new File("D:\\NewTestFile.txt"); inputStream = new FileInputStream(oldFile); outputStream = new FileOutputStream(newFile); byte[] buffer = new byte[1024]; int length; while ((length = inputStream.read(buffer)) > 0) { outputStream.write(buffer, 0, length); } inputStream.close(); outputStream.close(); System.out.println("File copied"); } catch (Exception e) { e.printStackTrace(); } } }
0 comments :
Post a Comment