Java File I/O exercise: copy the. Java File under a folder to The. txt File under another folder, .java.txt
Package com. swift; 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. IOException; import java. io. inputStreamReader; import java. io. outputStreamWriter; import java. io. unsupportedEncodingException; public class Copy_java_To_txt {public static void main (String [] Args) {/** copy the. Java file under a folder to The. txt file under another folder */try {StringBuffer sb = new StringBuffer (); BufferedReader br = new BufferedReader (new InputStreamReader (new FileInputStream ("e: \ neck \ test. java ")," UTF-8 "); String str; while (str = br. readLine ())! = Null) {System. out. println ("read a row from the file... "); sb. append (str); sb. append ("\ r \ n");} System. out. println ("successfully reading the file to the container" + "\ r \ n" + sb. toString (); String dir = "e: \ apple"; String fileName = "test.txt"; File file = new File (dir, fileName); if (! File. getParentFile (). exists () {System. out. println (file. getParentFile () + "the directory does not exist and will be created... "); file. getParentFile (). mkdirs ();} else {System. out. println ("directory exists, do not create... ");} BufferedWriter bw = new BufferedWriter (new OutputStreamWriter (new FileOutputStream (file)," UTF-8 "); bw. write (sb. toString (); bw. flush ();} catch (UnsupportedEncodingException e) {e. printStackTrace ();} catch (FileNotFoundException e) {e. printStackTrace ();} catch (IOException e) {e. printStackTrace ();}}}
The above specifies the file to be copied.
The following shows how to copy all the files ending with. java to another folder and rename them.
Use the following two lists
The list () method returns the names of all files and directories under a directory, and returns a String array.
The listFiles () method returns the absolute paths of all files and directories under a directory, and returns the File array.