File IO Operation in Java
Rohan Sakhale 6/27/2012 code-examplejava
# Summary
The following is a simple example on how to read & write data from a file. For Writing data we need following objects
File Object -> FileWriter Object -> PrintWriter Object
1
For Reading data we need following objects
File Object -> FileReader Object -> BufferedReader Object
1
# Screenshot
# Code
package com.rohansakhale.ioprogram;
import java.io.*;
/**
*
* @author Rohan Sakhale
*/
public class WriteReadDemo {
public static void main(String[] args) throws Exception{
// Lets create an object for writing data onto a file
// For that we will need object in following manner
// File -> FileWriter -> BufferedWriter -> PrintWriter
// PrintWriter will do all the job of writing data onto file
String filePath = "1rohan_test.txt";
// The best way to get the default directory of system
// for windows it chooses desktop for writing this file
File file = new File(filePath);
FileWriter fw = new FileWriter(file);
// fw tends to throw IOException
BufferedWriter bw = new BufferedWriter(fw);
PrintWriter pw = new PrintWriter(bw, true);
// true states to flush automatically
// if not set true you can use following line whenever you need to flush
// pw.flush();
pw.println("Rohan testing file writing");
pw.println("Using PrintWriter Class");
// The above lines should write data to file.
// For Vista & Seven users, make sure to select the path with file writable permissions
// Over here I used, My Documents path for file writing
// Lets read the written content from file onto console now
// For that you will need the following objects
// File -> FileReader -> BufferedReader
// we will use the same file object as above
FileReader fr = new FileReader(file);
// fr tends to throw IOException
BufferedReader br = new BufferedReader(fr);
String str = br.readLine(); // Reads the entire one line of text at once
while(str != null) // Checks if the string being read is not null
{
System.out.println(str);
str = br.readLine();
// Runs untill it does not reach end of file.
}
// Closing the opened string
bw.close();
br.close();
pw.close();
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65