我創建了一個程序,該程序可以創建一個目錄,然後在該目錄中放置一個文件。正如你所看到的,在這個人指定目錄之後,程序應該檢查目錄是否存在,如果目錄不存在或創建一個目錄,或者說已經有一個具有該目錄的目錄。每當我運行該程序,並且我放入一個已經存在的目錄時,而不是說該目錄已經存在,它會直接跳到失敗消息,並繼續在現有目錄中創建新文件。我該如何修復代碼,以便它能提供正確的「文件存在」消息,然後繼續執行代碼,而不是僅僅說出失敗消息?我的程序不執行if語句中的代碼
Please enter where you want your file...
/Users/FyuZheN/Desktop/test
[Console] Directory does not exist! Creating one...
[Console] Fail! Couldn't create directory!
[Console] What would you like to call your new file?
test.jar
[Console] Created new file test.jar
Successfully created new file: /Users/FyuZheN/Desktop/test/test.jar
此外,如果用戶指定的目錄是不能存在的目錄。這種情況發生......
Please enter where you want your file...
awdawdawd
[Console] Directory does not exist! Creating one...
[Console] Success! Created directory awdawdawd
[Console] What would you like to call your new file?
dawdawd
[Console] Created new file dawdawd
Successfully created new file: awdawdawd/dawdawd
我怎樣才能重新編碼,以便它給出了正確的錯誤消息,並再次要求用戶一個有效的目錄?
代碼:
import java.awt.*;
import java.io.*;
import java.util.*;
public class findFile {
public static void main (String[] args) throws IOException {
Scanner s = new Scanner(System.in);
boolean success = false;
System.out.println("Please enter where you want your file...");
String usrdir = s.nextLine();
File directory = new File(usrdir);
if (directory.exists() && directory.isFile()) {
System.out.println("[Console] This directory already exists");
} else {
System.out.println("[Console] Directory does not exist! Creating one...");
success = directory.mkdir();
if (success) {
System.out.println("[Console] Success! Created directory " + usrdir);
} else {
System.out.println("[Console] Fail! Couldn't create directory!");
}
}
System.out.println("[Console] What would you like to call your new file?");
String filename = s.next(filename = ".txt");
File f = new File(directory, filename);
if(f.exists() && f.isFile()) {
System.out.println("[Console] File already exists!");
} else {
System.out.println("[Console] Created new file " + filename);
success = f.createNewFile();
if (success) {
System.out.printf("Successfully created new file: %s%n", f);
} else {
System.out.printf("Failed to create new file: %s%n", f);
}
}
s.close();
}
}
添加一個while循環和布爾folderexists + if(folderexists){添加新文件}。 –
'isFile()'對於一個目錄來說總是爲false。也許你打算調用[isDirectory()](https://docs.oracle.com/javase/8/docs/api/java/io/File.html#isDirectory--)? – VGR
directory.exists()和directory.isFile()都必須返回true。因爲它從未進入該區域,這意味着其中一個或兩個都不能恢復正常。也許VGR或者''&&'應該是'||'?我對這裏的單詞文件的使用並不熟悉,因爲如果目錄包含一個文件,您可以跳過並且不要求文件? –