为什么不创建文件或为什么不能找到路径?

时间:2012-11-26 00:27:21

标签: java

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

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

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

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

2 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分: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());
}

此外,您错过了/路径as Alexey Feldgendler said中的根myFile