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