透過亂數產生100個小寫字母,並用FileWriter和BufferedWriter寫入至"rand_letters.txt"檔案中,然後再用FileReader和BufferedReader讀入並顯示在電腦螢幕上。以下為參考程式碼:
// Java FileReader / FileWriter
// file_char_rand.java
import java.io.*;
public class file_char_rand
{
public static void main (String[] args) throws IOException
{
FileWriter fw = new FileWriter("rand_letters.txt");
BufferedWriter bfw = new BufferedWriter(fw);
int a;
for(int i=1;i<=100;i++)
{
a = (int)(Math.random()*(122-97+1)+97); // ASCII(Dec)97~122:a~z
bfw.write((char)a);
bfw.newLine();
}
bfw.flush();
fw.close();
FileReader fr = new FileReader("rand_letters.txt");
BufferedReader bfr = new BufferedReader(fr);
String str;int count=0;
while((str=bfr.readLine())!=null)
{
count++;
System.out.print(str+" ");
if((count%10==0)&&(count!=0))
System.out.println();
}
System.out.println(count+" letters read");
fr.close();
}
}
輸出結果如下
沒有留言:
張貼留言