1. FileInputStream FileOutputStream通過字節流來讀寫文件
[java]
public static void main(String[] args) throws Exception {
//將文件裡寫數據
File f = new File("d:\\dmeo.txt");
FileOutputStream output = new FileOutputStream(f);
String s = "I Am Learning Java , 我在學習Java";
byte[] b = s.getBytes(); //將String變為byte數組
//output.write(b);write可以接收byte數組
for (int i = 0; i < b.length; i++) {
output.write(b[i]);
}
output.flush();
output.close();
//讀取文件裡數據
FileInputStream input = new FileInputStream(f);
//開辟一個文件大小的數組空間
byte[] in = new byte[(int) f.length()];
//將讀取來的字節放入數組中
for (int i = 0; i < in.length; i++) {
in[i] = (byte) input.read();
}
System.out.print(new String(in));
input.close();
}
2. BufferedInputStream BufferedOutPutStream 帶有緩存的讀寫字節流
[java]
public static void main(String[] args) throws Exception {
//將文件裡寫數據
File f = new File("d:\\dmeo.txt");
BufferedOutputStream output = new BufferedOutputStream(new FileOutputStream(f));
String s = "I Am Learning Java , 我在學習Java";
byte[] b = s.getBytes();
output.write(b); //默認會有512字節的緩存,當緩存存滿時一次性向文件中寫入
output.flush();
output.close();
BufferedInputStream input = new BufferedInputStream(new FileInputStream(f));
byte[] in = new byte[(int)f.length()];
for (int i = 0; i < in.length; i++) {
in[i] = (byte)input.read();
}
System.out.println(new String(in));
input.close();
}
2. DataInputStream DataOutputStream 可以讀寫基本數據類型的字節流
[java]
import java.io.*;
//一個簡單的人員類,只有姓名和年齡
public class Person {
private String name;
private int age;
public Person(String name ,int age){
this.name = name;
this.age = age;
}
public String getName(){
return this.name;
}
public int getAge() {
return this.age;
}
public static void main(String[] args) {
//構造對象數組
Person[] p1 = {new Person("Ryan",20),new Person("Tom",30),new Person("Jerry",15)};
File f = new File("d:\\demo\\demo.txt");
try {
DataOutputStream output = new DataOutputStream(new FileOutputStream(f));
//寫入數據
for (int i = 0; i < p1.length; i++) {
output.writeUTF(p1[i].getName()); //以UTF編碼寫入姓名
output.writeInt(p1[i].getAge()); //以Int型寫入年齡
}
output.flush();
output.close();
} catch (Exception e) {
e.printStackTrace();
}
Person[] p2 = new Person[p1.length];
try {
//讀出數據
DataInputStream input = new DataInputStream(new FileInputStream(f));
for (int i = 0; i < p1.length; i++) {
String name = input.readUTF(); //讀出姓名
int age = input.readInt(); //讀出年齡
//重新構造person對象
p2[i] = new Person(name,age);
}
input.close();
} catch (Exception e) {
e.printStackTrace();
}
//檢查是否還原正確
for (int i = 0; i < p2.length; i++) {
System.out.println("姓名:" + p2[i].getName() + " ;年齡:" + p2[i].getAge());
}
}
}<strong>
</strong>
2. PrintStream 將內存中的數據經過相應的轉換後再輸出
[java]
public static void main(String[] args){
File f = new File("d:\\dmeo.txt");
String studentName = "TOM";
int age = 20;
double totalScore = 600.0f;
PrintStream ps = null;
try {
ps = new PrintStream(new FileOutputStream(f));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
//格式化後輸出
ps.printf("姓名:%s , 年齡:%d , 總分:%3.1f",studentName,age,totalScore);
}