关于JAVA创建文件的问题..`编译没有出错,运行也正常`就是文件不能创建出来``用exits方法判断结果为false

来源:百度知道 编辑:UC知道 时间:2024/07/02 11:32:26
import java.io.*;
class FileTest
{
public static void main (String[] args) {
System.out.println("path separator"+File.pathSeparator);
System.out.println("separator"+File.separator);
System.out.println("separator char"+File.separatorChar);
File f=new File("dong1/aest1.txt");
System.out.println();
System.out.println(f);
System.out.println("exists? "+f.exists());
System.out.println("name "+f.getName());
System.out.println("path "+f.getPath());
System.out.println("absolutepath "+f.getAbsolutePath());
System.out.println("parent "+f.getParent());
System.out.println("is a file ? "+f.isFile());
System.out.println("is a directory "+f.isDirectory());
System.out.println("length "+f.length());
System.out.println("can read "+f.canRead());
Syste

你仅仅是创建了一个File对象,但并没有调用它创建文件的方法,因此是不能创建文件的,另外,看你的代码片段:

File f=new File("dong1/aest1.txt");

莫非你用的是Linux系统?Windows系统的文件分隔符是“\”,为了保证程序通用性,建议你把这一行修改成:

File f=new File("dong1"+File.separator+"aest1.txt");

再在它下面加上创建文件的代码:

f.createNewFile();

当然了,这样需要处理异常,完整的修改代码如下:

import java.io.*;
class FileTest
{
public static void main (String[] args) throws Exception {
System.out.println("path separator"+File.pathSeparator);
System.out.println("separator"+File.separator);
System.out.println("separator char"+File.separatorChar);
File f=new File("dong1"+File.separator+"aest1.txt");
f.createNewFile();
System.out.println();
System.out.println(f);
System.out.println("exists? "+f.exists());
System.out.println("name "+f.getName());
System.out.println(&qu