检查java中是否存在文件

时间:2022-12-12 16:48:50

So the following program should take in an input and output file as command line arguments.

因此,以下程序应将输入和输出文件作为命令行参数。

class FileCopy
{
public static void main(String[] args) throws IOException
{
    String infile = null;
    String outfile = null;
    BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in));    

    if (args.length >= 2) //both files given via command line
    {
        infile = args[0];
        if (fileExists(infile) == false)
        {
            infile = getInputFile();
        }
        outfile = args[1];
    }
    else if (args.length == 1) //input file given via command line
    {
        infile = args[0];
        outfile = getOutputFile(infile);
    }
    else //no files given on command line
    {
        infile = getInputFile();
        outfile = getOutputFile(infile);
    }

    //create file objects to use
    File in = new File(infile);
    File out = new File(outfile);

    /*
     *rest of code
     */
}

//get the input file from the user if given file does not exist
public static String getInputFile() //throws IOException
{
    BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in));
    String fileName = null;
    boolean haveFile = false;

    while(haveFile == false)
    {
        System.out.println("Enter a valid filename for input:");
        System.out.print(">> ");
        try
        {
            fileName = stdin.readLine();
        }
        catch (IOException e)
        {
            System.out.println("Caught exception: " + e);
        }
        haveFile = fileExists(fileName);
    }

    return fileName;    
}

//get the output file and test things
public static String getOutputFile(String infile)
{
    BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in));
    File input = new File(infile);
    String filename = null;
    boolean more = true;
    while(more)
    {
        System.out.println("Enter a valid filename for output:");
        System.out.print(">> ");
        try
        {
            filename = stdin.readLine();
        }
        catch (IOException e)
        {
            System.out.println("Caught exception: " + e);
        }
        File output = new File(filename);
        if (output.exists())
        {
            more = false;
        }
        if (filename == infile)
        {
            int selection;
            String inputString = null;

            System.out.println("The output file given matches the input file. Please choose an option:");
            System.out.println("1) Enter new filename");
            System.out.println("2) Overwrite existing file");
            System.out.println("3) Backup existing file");
            System.out.print(">> ");
            try
            {
                inputString = stdin.readLine();
            }
            catch (IOException e)
            {
                System.out.println("Caught exception: " + e);
            }
            selection = Integer.valueOf(inputString);
            switch (selection)
            {
                case 1: //new filename
                case 2: //overwrite
                case 3: //backup
                default: System.exit(0);
            }
        }
    }
    return null;
}

//check the given file to see if it exists in the current working directory
public static boolean fileExists(String n)
{
    return (new File(n)).exists();
}
}

2 个解决方案

#1


0  

One detail that I believe you have missed:

我相信你错过了一个细节:

When your program has only one argument (args.length == 1), i.e. when only the input file is defined, fileExists() is not called at all; infile is set to args[0] with no validation at all. You should probably add a specific check as you have done for the two-argument case.

当你的程序只有一个参数(args.length == 1)时,即只定义输入文件时,根本不调用fileExists(); infile设置为args [0],完全没有验证。您可能应该为两参数情况添加特定检查。

#2


0  

I've ran into a similar problem too. I was working under eclipse, and had to specify "src/file.txt" with my current directory having a file named "file" in the src directory.

我也遇到了类似的问题。我在eclipse下工作,不得不在我的当前目录中指定“src / file.txt”,在src目录中有一个名为“file”的文件。

Note: It was not named "file.txt" (this causes the string to be interpreted as "file.txt.txt"!).

注意:它没有命名为“file.txt”(这会导致字符串被解释为“file.txt.txt”!)。

Try testing against this program here assuming you have a file named "file" in your "src" directory:

假设您的“src”目录中有一个名为“file”的文件,请尝试对此程序进行测试:

import java.io.File;

public class FileChecker {

public static boolean Exists( String file ) 
{ 
    System.out.println("File being checked: " + file);
    return( (file.length()) > 0 && (new File(file).exists()) );
}

public static void main( String[] args ) 
{
    File dir = new File("src");

    System.out.println("List of files in source directory: ");
    if( dir.isDirectory()){
        File[] filenames = dir.listFiles();
        for( Object file : filenames ) {
            System.out.println(file.toString());
        }

    }
    else
        System.out.println("Directory does not exist.");

    if(FileChecker.Exists("src/file.txt"))
        System.out.println("File exists");
    else
        System.out.println("File does not exist");
}

}

It will print out the current files in source directory so you can see whether the file is really there or not, then you can test if it actually exists. Works on my end.

它将打印出源目录中的当前文件,以便您可以查看文件是否确实存在,然后您可以测试它是否确实存在。适用于我。

#1


0  

One detail that I believe you have missed:

我相信你错过了一个细节:

When your program has only one argument (args.length == 1), i.e. when only the input file is defined, fileExists() is not called at all; infile is set to args[0] with no validation at all. You should probably add a specific check as you have done for the two-argument case.

当你的程序只有一个参数(args.length == 1)时,即只定义输入文件时,根本不调用fileExists(); infile设置为args [0],完全没有验证。您可能应该为两参数情况添加特定检查。

#2


0  

I've ran into a similar problem too. I was working under eclipse, and had to specify "src/file.txt" with my current directory having a file named "file" in the src directory.

我也遇到了类似的问题。我在eclipse下工作,不得不在我的当前目录中指定“src / file.txt”,在src目录中有一个名为“file”的文件。

Note: It was not named "file.txt" (this causes the string to be interpreted as "file.txt.txt"!).

注意:它没有命名为“file.txt”(这会导致字符串被解释为“file.txt.txt”!)。

Try testing against this program here assuming you have a file named "file" in your "src" directory:

假设您的“src”目录中有一个名为“file”的文件,请尝试对此程序进行测试:

import java.io.File;

public class FileChecker {

public static boolean Exists( String file ) 
{ 
    System.out.println("File being checked: " + file);
    return( (file.length()) > 0 && (new File(file).exists()) );
}

public static void main( String[] args ) 
{
    File dir = new File("src");

    System.out.println("List of files in source directory: ");
    if( dir.isDirectory()){
        File[] filenames = dir.listFiles();
        for( Object file : filenames ) {
            System.out.println(file.toString());
        }

    }
    else
        System.out.println("Directory does not exist.");

    if(FileChecker.Exists("src/file.txt"))
        System.out.println("File exists");
    else
        System.out.println("File does not exist");
}

}

It will print out the current files in source directory so you can see whether the file is really there or not, then you can test if it actually exists. Works on my end.

它将打印出源目录中的当前文件,以便您可以查看文件是否确实存在,然后您可以测试它是否确实存在。适用于我。