0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Java_ファイルアクセスにtry-with-resourcesを使おう

Posted at

paizaラーニングforTEAM Java入門編
レッスン10の#10

10-#10
// ファイルアクセス - try-with-resources
import java.io.*;
import java.util.*;

public class Main {
    public static void main(String[] args) {

        File file = new File("articles.txt");

        // ファイル書き込み
        // try-with-resourcesでは、自動的にクローズしたいオブジェクトの部分をtryの()の中に記述する
        // 複数のコードがある場合はセミコロンで区切って記述する
        try(FileWriter filewriter = new FileWriter(file)) {
            filewriter.write("Hello world\n");
            filewriter.write("Hello Java\n");
            // filewriter.close();
        } catch (IOException e) {
            System.err.println("ファイル書き込みに失敗しました");
            e.printStackTrace();
        }

        // ファイル読み込み
        file = new File("error.txt");
        try(Scanner scan = new Scanner(file)) {
            while (scan.hasNextLine()) {
                String line = scan.nextLine();
                System.out.println(line);
            }
            // scan.close();
        } catch (FileNotFoundException e) {
            System.err.println("ファイル読み込みに失敗しました");
            e.printStackTrace();
        }
    }
}
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?