Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/306.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 我需要创建一个文件,它';这不是创造,而是我';我犯了一个错误_Java_File Handling - Fatal编程技术网

Java 我需要创建一个文件,它';这不是创造,而是我';我犯了一个错误

Java 我需要创建一个文件,它';这不是创造,而是我';我犯了一个错误,java,file-handling,Java,File Handling,我使用了try-catch方法,但我不熟悉这种方法。您的代码用于从文件读取。但如果要创建、写入和读取文件: 您可以尝试以下方法: 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 (FileNo

我使用了try-catch方法,但我不熟悉这种方法。

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

您可以尝试以下方法:

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

您的标题和代码似乎相反-您的代码正在读取文件顺便说一句,请发布StackTrace如果您的问题是您的代码打印了
FileNotFoundException
和一堆行信息,那是因为
e.printStackTrace()
就是这样做的。
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();
        }
    }
}