мне нужно создать файл, и он не создается, и я получаю сообщение об ошибке - PullRequest
0 голосов
/ 09 мая 2018
File file = new File("Skill.txt");

Scanner new_sc;
try {
    new_sc = new Scanner(file);
    while (new_sc.hasNextLine())
        System.out.println(new_sc.nextLine());
} catch (FileNotFoundException e) {
    e.printStackTrace();
}

Я использовал метод try catch, и я не знаком с этим методом.

1 Ответ

0 голосов
/ 09 мая 2018

Ваш код для чтения из файла. но если вы хотите создать, напишите и прочитайте файл:

Вы можете попробовать что-то вроде этого:

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;

public class Helper {

    public static void main(String[] args) {
        File fout = new File("Skill.txt");
        FileOutputStream fos;
        try {
              //Writing to the file
              fos = new FileOutputStream(fout);     
              BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(fos));
              bw.write("Writing to the file ...");
              bw.newLine();
              bw.close();

              //Reading from file
              Scanner new_sc = new Scanner(fout);

              while (new_sc.hasNextLine())
                  System.out.println(new_sc.nextLine());

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
...