ファイル操作1
ポイント:
ディレクトリ、ファイルが作成できるか
例外処理ができているか
ファイルに書き込みができているか
プログラムは簡潔で分かりやすいか
問題
java-musashiurawa.hatenablog.com
解答
import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.util.Scanner; public class filesousa1 { public static void main(String[] args) { // TODO 自動生成されたメソッド・スタブ Scanner scan = new Scanner(System.in); String fileName = "schedule.csv"; //ディレクトリ名を取得 System.out.print("名前を入力してください:"); String userName = scan.nextLine(); //ディレクトリを作成する String path = "c:\\JavaTest\\" + userName; File newdir = new File(path); boolean checkdirectory = newdir.exists(); if(checkdirectory == false) { newdir.mkdir(); //新規の場合、ファイルを作成 try { File newfile = new File(path + "\\" + fileName); newfile.createNewFile(); }catch(IOException e) { System.out.println(e); } } //スケジュールを入力 try { File file = new File(path + "\\" + fileName); PrintWriter pw = new PrintWriter(new BufferedWriter(new FileWriter(file,true))); if(checkdirectory == false) { String koumoku[] = {"日付:","予定:","開始時間:","終了時間:","備考:"}; for(int i = 0; i < koumoku.length; i++) { pw.print(koumoku[i]); if(i != koumoku.length - 1) { pw.print(","); } } pw.println(); System.out.println("ようこそ" + userName + "さん。"); } String schedule_continue; do { schedule_tuika(pw); schedule_continue = scan.nextLine(); }while(schedule_continue.equals("はい")); System.out.println("スケジュール入力を終了します。"); pw.close(); }catch(IOException e) { System.out.println(e); } } private static void schedule_tuika(PrintWriter pw) { Scanner scan = new Scanner(System.in); String koumoku[] = {"日付:","予定:","開始時間:","終了時間:","備考:"}; int j; System.out.println("スケジュールを入力してください。"); for(j = 0; j < koumoku.length; j++) { System.out.print(koumoku[j]); String schedule = scan.nextLine(); pw.print(schedule); if(j != koumoku.length - 1) { pw.print(","); } } pw.println(); System.out.println("予定を入れました。"); System.out.println("引き続き予定を入れる場合は「はい」と入力してください。"); System.out.print("予定を入れる:"); } }