簡體   English   中英

檢查Java中是否存在文件

[英]Checking if a file exists in java

因此,以下程序應將輸入和輸出文件作為命令行參數。

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();
}
}

我相信您錯過了一個細節:

當程序只有一個參數( args.length == 1 )時,即僅定義輸入文件時, fileExists()不調用fileExists() infile設置為args[0] ,完全沒有驗證。 你應該添加一個特定的檢查,你已經做了兩個參數的情況下。

我也遇到了類似的問題。 我在eclipse下工作,必須在當前目錄中指定“ src / file.txt”,在src目錄中有一個名為“ file”的文件。

注意:它沒有命名為“ file.txt”(這導致字符串被解釋為“ file.txt.txt”!)。

假設您在“ 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");
}

}

它將在源目錄中打印出當前文件,以便您可以查看該文件是否確實存在,然后可以測試該文件是否確實存在。 對我有效。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM