ディレクトリを作成し、そのディレクトリにファイルを配置できるプログラムを作成しています。見ての通り、人がディレクトリを指定した後、プログラムはディレクトリが存在するか存在しないかをチェックし、存在しない場合はディレクトリを作成するか、またはその名前のディレクトリが既に存在すると判断します。私がプログラムを実行し、既に存在するディレクトリを置くと、そのディレクトリが既に存在していると言っているのではなく、失敗メッセージにまっすぐにスキップして、既存のディレクトリに新しいファイルを作成します。どのようにコードを修正して、適切な「ファイルが存在します」というメッセージを表示してから、失敗メッセージを表示するのではなくコードを実行しますか?私のプログラムは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ループとbooleanを追加します。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を返す必要があります。その地域に入ることは決してないので、どちらかまたは両方が真実を返さないことを意味します。おそらくあなたの '&&'は '||'でなければならないでしょうか?私はここに言葉のファイルの使用に精通していないよ、あなたが先に飛び越してファイルを要求しないファイルがディレクトリに含まれているように思えるだろうか? –