【问题标题】:i need to create a file and it's not creating and i'm getting an error我需要创建一个文件,但它没有创建,我收到一个错误
【发布时间】:2018-05-09 08:03:04
【问题描述】:
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方法,对这个方法不熟悉。

【问题讨论】:

  • 您的标题和您的代码似乎相反-您的代码正在读取文件
  • 顺便说一句,请发布您的堆栈跟踪
  • 如果您的问题是您的代码打印了FileNotFoundException 和一堆行信息,那是因为e.printStackTrace() 就是这样做的。

标签: java file-handling


【解决方案1】:

您的代码用于从文件中读取。但如果你想创建、写入和读取文件:

你可以试试这样的:

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();
        }
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-01-18
    • 2018-05-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-07
    • 2018-02-26
    • 1970-01-01
    相关资源
    最近更新 更多