面向物件程式設計(Java)實驗6
阿新 • • 發佈:2022-04-22
實驗要求
- 在C盤根目錄建立文字檔案Hello.txt,並往裡寫入若干行文字。從Hello.txt中讀取文字並顯示在螢幕上。
實驗內容
package test6; import java.io.*; import java.util.Scanner; public class hello { public static void main(String [] args) throws IOException{ try { FileReader fr = new FileReader("D:\\作業\\JAVA學習\\JAVA實驗報告\\Hello.txt"); FileWriter fr2 = new FileWriter("D:\\作業\\JAVA學習\\JAVA實驗報告\\Hello.txt"); BufferedReader fw = new BufferedReader(fr); BufferedWriter fw2 = new BufferedWriter(fr2); int line; String str; Scanner input = new Scanner(System.in); System.out.println("你要輸入文字的行數為:"); line = input.nextInt(); for(int i=0;i<line;i++){ str = input.next(); fw2.write(str); if(i!=line-1) { fw2.newLine(); } } fw2.close(); str = fw.readLine(); while(str!=null){ System.out.println(str); str = fw.readLine(); } fw.close(); } catch (IOException ioe){ System.out.println("Error : " + ioe); } } }