寫一個程式,把文件檔的內容讀取出來
import java.io.IOException;
import java.io.FileReader;
import java.io.BufferedReader;
class Print{
public static void main(String[] args) throws IOException{
FileReader f =new FileReader("d:\\MyWriter.txt");
FileReader f1 =new FileReader("d:\\MyWriter.txt");
BufferedReader b = new BufferedReader(f);
BufferedReader b1 = new BufferedReader(f1);
String s;
int i=0;
int j=0;
while((s = b.readLine())!=null){
++i;
}
b.close();
//用變數i來統計總共幾筆資料
String[][] t =new String[10][];
while((s = b1.readLine())!=null){
t[j]=s.split(":");
++j;
}
b1.close();
//逐行讀取,切割分開後用陣列方式存放
for(int k=0;k<i;k++){
System.out.println(t[k][0]+":"+t[k][1]);
}
}
}
執行結果:
jack:10
mary:20
tom:30
mark:40
透過把檔案丟到陣列再進行讀取,但實際上不用用到這麼麻煩
import java.io.IOException;
import java.io.FileReader;
import java.io.BufferedReader;
class Print{
public static void main(String[] args) throws IOException{
FileReader f =new FileReader("d:\\MyWriter.txt");
BufferedReader b = new BufferedReader(f);
String s;
while((s = b.readLine())!=null){
System.out.println(s);
}
b.close();
//這邊改為判斷檔案非空值就列印,如此也可以做到印出整個文件
}
}
執行結果:
jack:10
mary:20
tom:30
mark:40
2012年12月16日 星期日
檔案的寫入
寫一個程式,可以儲存人名和成績
import java.util.Scanner;
import java.io.FileWriter;
import java.io.IOException;
class Write{
public static void main(String[] args)throws IOException{
FileWriter f = new FileWriter("d:\\MyWriter.txt", true);
//透過FileWriter來指定位置跟存入一個檔案
Scanner s = new Scanner(System.in);
System.out.println("請輸入性名");
String name = s.nextLine();
System.out.println("請輸入分數");
int sc = s.nextInt();
f.write(name+":"+sc+"\n");
f.close();
}
}
執行後生成一個檔案
檔案內容:
jack:10
mary:20
tom:30
mark:40
import java.util.Scanner;
import java.io.FileWriter;
import java.io.IOException;
class Write{
public static void main(String[] args)throws IOException{
FileWriter f = new FileWriter("d:\\MyWriter.txt", true);
//透過FileWriter來指定位置跟存入一個檔案
Scanner s = new Scanner(System.in);
System.out.println("請輸入性名");
String name = s.nextLine();
System.out.println("請輸入分數");
int sc = s.nextInt();
f.write(name+":"+sc+"\n");
f.close();
}
}
執行後生成一個檔案
檔案內容:
jack:10
mary:20
tom:30
mark:40
訂閱:
文章 (Atom)