2016-04-13 45 views
-2

请帮助,我需要帮助如何检查有效的文件名。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添加到他们输入的名称?或者如何检查文件是否有效?任何帮助将非常感激。

+0

使用[String#endsWith](https://docs.oracle.com/javase/7/docs/api/java/lang/String.html#endsWith%28java.lang.String%29)并检查用户输入一个以“.txt”结尾的字符串。 – Norsk

+1

['File.canRead()'](https://docs.oracle.com/javase/8/docs/api/java/io/File.html#canRead--)'if(file.canRead() )'? –

+0

这取决于你的意思***有效***。你的意思是他们输入的格式是有效的文件名吗?或者你的意思是说他们输入了真正存在的文件的名称?请明确说明。 –

回答

2

你可以试试这个

File file = new File(filename); 
// If file doesn't exist then close application... 
if (!file.exists()) { System.exist(0); } 

希望这有助于。

0

尝试连接用户的输入字符串,方法是加入.txt。它应该工作。此外

if (!fileName.trim().toLowerCase().endsWith(".txt")) { 
    fileName+= ".txt"; 
} 

,如果你想知道,如果该文件已经存在或不: