mark

mark

过程中发生的所有异常都是IOException的子类。

字节流

文件输入流

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
import java.io.*;

public class ByteReader {
public static void main(String[] arguments) {
try (
FileInputStream file = new
FileInputStream("save.gif")
) {

boolean eof = false;
int count = 0;
while (!eof) {
int input = file.read();
System.out.print(input + " ");
if (input == -1)
eof = true;
else
count++;
}
file.close();
System.out.println("\nBytes read: " + count);
} catch (IOException e) {
System.out.println("Error -- " + e.toString());
}
}
}

文件输出流

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
import java.io.*;

public class ByteWriter {
public static void main(String[] arguments) {
int[] data = { 71, 73, 70, 56, 57, 97, 13, 0, 12, 0, 145, 0,
0, 255, 255, 255, 255, 255, 0, 0, 0, 0, 0, 0, 0, 44, 0,
0, 0, 0, 13, 0, 12, 0, 0, 2, 38, 132, 45, 121, 11, 25,
175, 150, 120, 20, 162, 132, 51, 110, 106, 239, 22, 8,
160, 56, 137, 96, 72, 77, 33, 130, 86, 37, 219, 182, 230,
137, 89, 82, 181, 50, 220, 103, 20, 0, 59 };
try (FileOutputStream file = new
FileOutputStream("pic.gif")) {

for (int i = 0; i < data.length; i++) {
file.write(data[i]);
}
file.close();
} catch (IOException e) {
System.out.println("Error -- " + e.toString());
}
}
}

字符流

读取文本文件

例一:

1
2
3
4
5
6
7
8
9
10
11
12
13
import java.io.*;
public class FileCopy {
public static void main(String args[]) throws IOException{
FileReader f1;
FileWriter f2;
f1=new FileReader("FileCopy.java");
f2=new FileWriter("acopy_of_java_file.java");
int temp;
while((temp=f1.read())!=-1);
f2.write(temp);
f1.close(); f2.close(); }
public FileCopy() { }
}

例二:

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
import java.io.*;

public class SourceReader {
public static void main(String[] arguments) {
try (
FileReader file = new
FileReader("SourceReader.java");
BufferedReader buff = new //这是讲读取的字符存储到缓冲区,以提高效率。
BufferedReader(file)) {

boolean eof = false;
while (!eof) {
String line = buff.readLine();
if (line == null) {
eof = true;
} else {
System.out.println(line);
}
}
buff.close();
} catch (IOException e) {
System.out.println("Error -- " + e.toString());
}
}
}