5. 文件流
從文件系統中的某個文件中獲取數據
1.1 文件字節流,如圖像
FileInputStream
FileOutputStream
1.2 文件字符流
FileReader
FileWriter
1.3 實例
public class Test {
// 1. 測試字節文件輸出流
static void test1(){
try {
OutputStream out = new FileOutputStream("src\\temp.txt");
String str = "http://www.geek99.com";
byte[] b = str.getBytes();
out.write(b);
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
// 2. 測試字節文件輸入流
static void test2(){
try {
InputStream in = new FileInputStream("src\\temp.txt");
int a;
while((a = in.read())!=-1)
System.out.print((char)a);
in.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
// 3. 字符文件輸出流
static void test3(){
try {
Writer w = new FileWriter("src\\temp.txt");
w.write("http://www.geek99.com");
w.close();
} catch (IOException e) {
e.printStackTrace();
}
}
// 4. 字符文件輸入流
static void test4(){
try {
Reader r = new FileReader("src\\temp.txt");
int a;
while((a=r.read())!=-1)
System.out.print((char)a);
r.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
test4();
}
}
原文出處:http://geek99.com/node/459#
該博客教程視頻地址:http://geek99.com/node/1655