请帮助,我需要帮助如何检查有效的文件名。Java检查虚拟文件
这是我的计划的一部分......
import java.util.Scanner;
import java.io.File;
import java.io.IOException;
public class BookstoreInventory
{
public static void main(String[] args)throws IOException
{
//Vaiable declartions
int edition, quanity;
double pricePerBook;
String isbn, author, title, publisherCode;
int totalQuant = 0;
double total = 0;
double totalValue = 0;
double sumOfPriceBook = 0;
//Scanner object for keyboard input
Scanner keyboard = new Scanner(System.in);
//Get the file name from the user
System.out.print("Enter the name of the file: ");
String filename = keyboard.nextLine();
//Open the file and set delimiters
File file = new File(filename);
Scanner inputFile = new Scanner(file);
inputFile.useDelimiter("_|/|\\r?\\n");
}
}
所以在我的节目我不知道我会怎么检查,看看它是否是一个有效的文件。例如,当用户输入文件名称的“库存”时,这将产生错误,因为文件名需要.txt,所以用户应该输入“inventory.txt”。那么有没有办法将.txt添加到他们输入的名称?或者如何检查文件是否有效?任何帮助将非常感激。
使用[String#endsWith](https://docs.oracle.com/javase/7/docs/api/java/lang/String.html#endsWith%28java.lang.String%29)并检查用户输入一个以“.txt”结尾的字符串。 – Norsk
['File.canRead()'](https://docs.oracle.com/javase/8/docs/api/java/io/File.html#canRead--)'if(file.canRead() )'? –
这取决于你的意思***有效***。你的意思是他们输入的格式是有效的文件名吗?或者你的意思是说他们输入了真正存在的文件的名称?请明确说明。 –