Académique Documents
Professionnel Documents
Culture Documents
html
Java Notes
1 // File: io/readwrite/CopyTextFile.java
2 // Description: Example to show text file reading and writing.
3 // Author: Fred Swartz
4 // Date : February 2006
5
6 import java.io.*;
7 import java.util.*;
8
9 public class CopyTextFile {
10
11 public static void main(String args[]) {
12 //... Get two file names from use.
13 System.out.println("Enter a filepath to copy from, and one to copy to.");
14 Scanner in = new Scanner(System.in);
15
16 //... Create File objects.
17 File inFile = new File(in.next()); // File to read from.
18 File outFile = new File(in.next()); // File to write to
19
20 //... Enclose in try..catch because of possible io exceptions.
21 try {
22 copyFile(inFile, outFile);
23
24 } catch (IOException e) {
25 System.err.println(e);
26 System.exit(1);
27 }
28 }
29
30
31 //=============================================================== copyFile
32 // Uses BufferedReader for file input.
33 public static void copyFile(File fromFile, File toFile) throws IOException {
34 BufferedReader reader = new BufferedReader(new FileReader(fromFile));
35 BufferedWriter writer = new BufferedWriter(new FileWriter(toFile));
36
37 //... Loop as long as there are input lines.
38 String line = null;
39 while ((line=reader.readLine()) != null) {
40 writer.write(line);
41 writer.newLine(); // Write system dependent end of line.
42 }
43
44 //... Close reader and writer.
45 reader.close(); // Close to unlock.
46 writer.close(); // Close to unlock and flush to disk.
47 }
1 of 2 11-Jun-10 4:49 PM
Java: File I/O - Text Files http://leepoint.net/notes-java/io/10file/10readfile.html
48
49
50 //=============================================================== copyFile2
51 // Uses Scanner for file input.
52 public static void copyFile2(File fromFile, File toFile) throws IOException {
53 Scanner freader = new Scanner(fromFile);
54 BufferedWriter writer = new BufferedWriter(new FileWriter(toFile));
55
56 //... Loop as long as there are input lines.
57 String line = null;
58 while (freader.hasNextLine()) {
59 line = freader.nextLine();
60 writer.write(line);
61 writer.newLine(); // Write system dependent end of line.
62 }
63
64 //... Close reader and writer.
65 freader.close(); // Close to unlock.
66 writer.close(); // Close to unlock and flush to disk.
67 }
68 }
GUI interface
javax.swing.JFileChooser creates a standard file dialog and allows you to easily get a File object for reading
or writing. See JFileChooser.
2 of 2 11-Jun-10 4:49 PM