/* * Regards to file operation */ import java.io.*; import java.text.SimpleDateFormat; class FileRelated{ public static void main(String args[]){ String s = "Something to write."; FileOutputStream fos = null; FileInputStream fis = null; BufferedInputStream bis = null; try{ //* // To create a file File file = new File("afile.txt");// or "E:\\afile.txt" to specify the directory if (file.createNewFile()) System.out.println("File is created successfully."); else System.out.println("File is already existed."); //*/ //* // Write to a file >>> FileOutputStream vs. BufferedWriter // File file = new File("afile.txt");// >> to connect to a file fos = new FileOutputStream(file); // throws FileNotFoundException if(!file.exists()){ file.createNewFile(); } byte[] bytes = s.getBytes(); fos.write(bytes); fos.flush(); fos.close(); System.out.println("File written successfully."); //*/ //* // Read a file >>> BufferedInputStream vs. BufferedReader //File file = new File("afile.txt");// >> to connect to a file fis = new FileInputStream(file); // throws FileNotFoundException bis = new BufferedInputStream(fis); while(bis.available() > 0){ System.out.print((char)bis.read()); }//while fis.close(); bis.close(); //*/ //* // Append content to a file >>> (BufferedWriter, FileWriter), PrintWriter FileWriter fw = new FileWriter(file, true); BufferedWriter bw = new BufferedWriter(fw); bw.write("\nSomething more......"); bw.close(); System.out.println("Append Successfully."); // try PrintWriter...... //*/ PrintWriter pw = new PrintWriter(file); pw.write("Write something using PrintWriter..."); pw.append("\nMore to write......"); pw.print("\nPrint can automatically append......"); pw.flush(); pw.close(); //* // Get the last modified Date >> import java.text.SimpleDateFormat; SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss"); //System.out.println(file.lastModified()); System.out.println("Last Modified Date: " + sdf.format(file.lastModified())); //*/ /* // Rename a file...... File file2 = new File("bfile.txt"); boolean flag = file.renameTo(file2); if(flag) System.out.println("Rename Successfully."); else System.out.println("Rename failed."); //*/ /* // Delete a file >> make sure all the connections are close() before delete if(file.delete()){ System.out.println(file.getName() + " is deleted."); }else{ System.out.println("Delete failed."); }//else //*/ }catch(FileNotFoundException e){ // Need to be previous to IOException or simply use IOException e.printStackTrace(); }catch(IOException e){ e.printStackTrace(); }catch(Exception e){ e.printStackTrace(); }finally{ /* try{ // You may move this part to the other try clause fos.close(); fis.close(); bis.close(); }catch(IOException ioe){ System.out.println("Error in closing file."); }//catch //*/ }//catch }//main() }//FileRelated