在 java 中创建文件的奇怪行为
Strange behavior of file creating in java
我这里有这段代码可以创建一个文件,如果不存在并写入 it.Its 行为是 strange.It 一次创建它而不是另一个,无论我在哪个文件夹中创建 it.It 可能是个小错误,但我无法理解。
有时它会生成文件,但无法读取。
import java.io.*;
import java.util.Arrays;
import java.util.Scanner;
public class Main {
public static void main(String[] args){
File file = new File("C:\Users\lenovo\Desktop\testfile.txt");
Scanner fileScanner = null;
try {
fileScanner = new Scanner(file);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
if (!file.isFile()){
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
PrintWriter pw = null;
try {
pw = new PrintWriter(file);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
pw.println("hello world\n");
pw.append("how si it going?\n");
pw.append("checkingggg");
pw.close();
// while (fileScanner.hasNext()){
// System.out.println(fileScanner.nextLine());
//}
}
}
这里没有奇怪的行为。您正在尝试读取一个不存在的文件。你正在然后尝试通过各种冗余方式创建它,但已经太晚了。
您的代码没有意义。
我这里有这段代码可以创建一个文件,如果不存在并写入 it.Its 行为是 strange.It 一次创建它而不是另一个,无论我在哪个文件夹中创建 it.It 可能是个小错误,但我无法理解。 有时它会生成文件,但无法读取。
import java.io.*;
import java.util.Arrays;
import java.util.Scanner;
public class Main {
public static void main(String[] args){
File file = new File("C:\Users\lenovo\Desktop\testfile.txt");
Scanner fileScanner = null;
try {
fileScanner = new Scanner(file);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
if (!file.isFile()){
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
PrintWriter pw = null;
try {
pw = new PrintWriter(file);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
pw.println("hello world\n");
pw.append("how si it going?\n");
pw.append("checkingggg");
pw.close();
// while (fileScanner.hasNext()){
// System.out.println(fileScanner.nextLine());
//}
}
}
这里没有奇怪的行为。您正在尝试读取一个不存在的文件。你正在然后尝试通过各种冗余方式创建它,但已经太晚了。
您的代码没有意义。