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

问题描述 投票:0回答:5

i有一个程序,该程序从目录中选择最新文件并将其压缩为一个文件。但是如果目录中没有文件,我想停止程序,并显示错误消息,例如“ deirectory中没有文件”

我尝试附加此内容:

如果(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();
}
    }}}
java file exit
5个回答
2
投票

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

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

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

1
投票

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

System.exit(0);

希望有所帮助。


1
投票

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

如果确实指向目录,并且目录为空,则只需从listFiles返回一个空数组。所以你可以使用

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

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
}

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...")
© www.soinside.com 2019 - 2024. All rights reserved.