如果使用java文件夹中不存在文件,如何停止程序?

时间:2011-02-26 22:57:21

标签: java file exit

我有一个程序从目录中选择最近的文件并将它们压缩成一个文件。 但我想停止程序,如果目录中没有文件,并显示错误消息,如“目录中没有文件”

我尝试追加这个:

如果(file.exists) {} 其他 {}

但我不知道如何将其插入我的代码中。

谢谢

{
    String source = "C:/Source";
    String target = "C:/Target";

    File sourceDir = new File(source);
    File[] files = sourceDir.listFiles();

    if(files.exists())

    Arrays.sort(files, new Comparator<File>()
    {
        public int compare(File f1, File f2)
        {
            return (int) (f2.lastModified() - f1.lastModified());
        }
    });

    // create the target directory
    File targetDir = new File(target);
    targetDir.mkdirs();

{  
    for(int i=0, length=Math.min(files.length, 12); i<length; i++)
        files[i].renameTo(new File(targetDir, files[i].getName()));


     PrintWriter pw = new PrintWriter(new FileOutputStream("C:/Joined/joined.txt"));
    File file = new File("C:/Target");

    File[] files2 = file.listFiles();

    for (int i = 0; i < files2.length; i++)
    {

      File currentFile = files2[i];

      System.out.println("Processing " + currentFile.getPath() + "... ");

      BufferedReader br = new BufferedReader(new FileReader(currentFile));

      String line = br.readLine();

      while (line != null)
      {
        pw.println(line);
        line = br.readLine();
      }
      br.close();
    }
    pw.close();

 Thread.sleep(2000);
try
{
    ProcessBuilder pb = new ProcessBuilder("c:\\Joined\\Join.bat");
   Process p = pb.start();

}
catch (IOException e)
 {
e.printStackTrace();
}
    }}}

5 个答案:

答案 0 :(得分:2)

不使用System.exit()方法,最好使用guard子句来阻止进一步执行。使用System.exit()不是一个好习惯,因为它会突然停止流程。理想的解决方案是

if (file.exists()) 
   return; //Use appropriate returns according to the method signature.

// Block of code that does something with the file.

答案 1 :(得分:1)

您可以尝试像这样调用方法退出:

System.exit(0);

希望有所帮助。

答案 2 :(得分:1)

如果sourceDir未引用目录,您将从null获得listFiles,这是您可以检查的第一件事。

如果它确实引用了一个目录,并且该目录为空,那么您只需从listFiles返回一个空数组。所以你可以使用

if (files.length() == 0) {
    System.err.println("There is no files in the deirectory");
    System.exit(-1);
}

答案 3 :(得分:0)

File[] files2 = file.listFiles();

你可以做到

if(files2.length == 0)
{
    System.err.println("Error - no files found!");

如果您希望程序完全关闭,

    System.exit(1); //0 denotes normal close, 1 denotes an error
}

如果您希望程序继续下一步,

    break; //exit the current loop
}

答案 4 :(得分:0)

if(files.exists())之后,请确保在您刚刚提到的所有代码块中都包含方括号({}

例如:

if(files.exists()) {
    // code you want it to run if files exist
} else System.err.println("No Files Exist In This Directory...")