0

所以我正在创建以下代码来创建一个新文件。有谁知道它为什么抛出异常?

本质上,我认为它会在使用构造函数后检查文件是否存在,但它不存在,我认为它会创建它,但都没有发生。

Java Code:


import java.util.Scanner;
import java.lang.Integer;
import java.io.*;
import java.lang.*;
import java.io.File;

class CreateNumberFile{
    public static void main(String args[]){
        //Ask user for filename and highest number
        Scanner in = new Scanner(System.in);
        System.out.println("Enter the filename");
        String fileName = in.next();
        System.out.println("Enter the highest number for this file");
        int maxNumber = in.nextInt();

        System.out.print("A file titled " + fileName+ " will be created containing a");
        System.out.println(" string of numbers with numbers ranging from 0 to: " + maxNumber);

        // Create a File object 
        File myFile = new File("home/Users/Joe/Dropbox/Programming/Java/Projects/g2.txt");
        // Tests whether the file or directory denoted by this abstract 
        //pathname exists.
        if (myFile.exists()) {
            System.out.println(myFile.getAbsolutePath() +
                    " File already exists");

        } else {
          try{
            //creates a new, empty file named by this pathname
            myFile.createNewFile();
            System.out.println(myFile.getAbsolutePath() + 
                    " File Created Successfully");
          } catch(IOException e){
            System.err.println ("Caught IOException "+e.getMessage());
          }
        }

    }//main
}//class

当我运行它时,我收到以下错误:

输出:

Caught IOException The system cannot find the path specified

我认为代码会检查文件是否存在,如果不存在,我会使用构造函数来创建文件?有任何想法吗?

4

2 回答 2

0

您的路径看起来像一条绝对路径,但您似乎忘记了开头的斜线。

于 2012-11-26T00:29:49.973 回答
0

如果你的文件没有exist(),它的父文件也可能没有exist(),所以你应该创建它们:

try {
    // create all dirs needed to myFile's parent to exist()
    myFile.getParent().mkdirs();
    //creates a new, empty file named by this pathname
    myFile.createNewFile();
    System.out.println(myFile.getAbsolutePath() + " File Created Successfully");
} catch(IOException e) {
    System.err.println ("Caught IOException "+e.getMessage());
}

此外,正如 Alexey Feldgendler 所说,您缺少路径/中的根。myFile

于 2012-11-26T00:34:06.703 回答