【问题标题】:an if statements blanks the outputif 语句使输出空白
【发布时间】:2013-11-27 05:49:33
【问题描述】:

我正在尝试显示符号化项目列表并让用户选择要删除的项目。

  1. 我将信息写入 txt 文件。
  2. 我将文件的内容存储在一个数组中。
  3. 我打印出数组。
  4. 用户输入(例如 L101),它将被删除 文件。

问题出在步骤(1) 当且仅当文件不存在时,我希望写入文件。 所以我在 while 循环之前,它将用

写入文件
if(file.isFile() ==false).

然而,这似乎使输出空白,就好像阅读器无法读取文件并将其存储在数组中一样。为什么? P.S 如果我不放 if 和 else 语句,输出是好的,只是它再次写入文件,我不想发生这种情况,我希望 ti 显示除用户键入的内容之外的所有内容。

这是代码

public static void main (String args[]) throws IOException
{
    //Declaring the file
     File tempFile = new File("D:\\myTempFile.txt");
    //Declaring the writer
     BufferedWriter writer = new BufferedWriter(new FileWriter(tempFile));
    int n=0;
    int L=1;
    //Writing to the file if it did not exist
    if(tempFile.isFile()==false) 
    {

    while(n<15 && L<3)
        {
        n++;
        writer.write("L"+L+"0"+n);
        writer.newLine();
        L++;
        writer.write("L"+L+"0"+n);
        writer.newLine();
        L++;
        writer.write("L"+L+"0"+n);
        writer.newLine();
        L=1;
        //}

    }
     writer.close(); 
     freeParkingSpaces();
    }
    //read the and store to array if the file exists
    else if(tempFile.isFile()==true)
    {
        freeParkingSpaces();
    }

}                

public static void freeParkingSpaces() throws IOException
   {
     File tempFile = new File("D:\\myTempFile.txt");
   //using try and catch to handle errors and print propriet message instead. 
    try{ 
        Scanner readSpaces; // declare scanner variable.
//reading from file that contains the available spaces and storing them into an array.
System.out.println("Please choose one of the following parking spaces: ");
System.out.println(" ");
String [] freeSpaces= new String[45]; // declaring the array.
int i=0;

//getting input from file that contains the available spaces and storing them into an    array.
readSpaces=new Scanner(new File("D://myTempFile.txt")); 
System.out.print("\t\t");

//Display the values of the array which are the available spaces.
while(i<15 && readSpaces.hasNext()){
freeSpaces[i]=readSpaces.nextLine();
System.out.print("   "+freeSpaces[i]);
i++;
}
System.out.println(" ");
System.out.print("\t\t");
while(i>=15&&i<30&&readSpaces.hasNext()){
freeSpaces[i]=readSpaces.nextLine();
System.out.print("   "+freeSpaces[i]);
i++;
}
System.out.println(" ");
System.out.print("\t\t");
while(i>=30&&i<45&&readSpaces.hasNext()){
freeSpaces[i]=readSpaces.nextLine();

System.out.print("   "+freeSpaces[i]);
i++;
}
System.out.println(" ");
readSpaces.close();

//create scanner object to hold the input of a user which is a park space.
Scanner holder5=new Scanner(System.in); 
System.out.print("Your choice:  ");
String spaceName=holder5.nextLine();

//declaring files

File inputFile=new File("D://Temporary.txt");

// creating object to read from Free_ParkingSpaces file
BufferedReader reader=new BufferedReader(new FileReader(tempFile));
// creating object to write to the tempFile
BufferedWriter writer0=new BufferedWriter(new FileWriter(inputFile));
String currentLine;

while((currentLine = reader.readLine()) != null){
String trimmedLine = currentLine.trim();  
if(trimmedLine.equals(spaceName)) continue;//leave the required space by the user.
writer0.write(currentLine);   //write the lines to the tempFile.
writer0.newLine();   // start from new line.
}

writer0.close(); //close BufferedWriter Object

reader.close(); //close BufferedReader Object
tempFile.delete();  // Delete the old available spaces file.
inputFile.renameTo(tempFile); // Naming the temp file myTempFile.

System.out.println("Registration has completed successfuly");}


                                    catch(Exception e){
                        System.out.println("\n\t\t\t\tSorry, there's something     wrong try again!");}
                   }
}

【问题讨论】:

  • 欢迎来到 Stack Overflow。你已经发布了一百多行代码——而且它的格式非常难以阅读。您能否尝试将其简化为仍然演示问题的最小示例,然后将其格式化,并将其编辑到问题中?

标签: java arrays while-loop filereader


【解决方案1】:

isFile() 检查它是否是文件(不是目录)

exists() 检查文件是否存在。

http://docs.oracle.com/javase/7/docs/api/java/io/File.html

改变它。此外,在使用之前,请务必阅读有关该方法的文档并确切了解其用途。

注意,如果语句采用布尔值,所以 if(file.exists()){}if(file.isFile()){} 是正确的方法

编辑:

由于您仍然无法将数据放入文件中,因此您应该这样做。

首先,处理IOException。当您执行 throws IOException 时,您基本上是在说您将在更高级别处理异常,但 main 也声明了这一点,因此永远不会捕获异常(使用 IDE 和自动更正学习时的问题之一) .

要做到这一点,您需要这样做:

1) 删除所有throws IOException

2) 将捕获更改为

 try{
    //...
 } catch(IOException ioe){
     ioe.printStackTrace();
 } catch(Exception e){
     System.out.println("\n\t\t\t\tSorry, there's something     wrong try again!");
     System.out.println("\n\t\t\t\tReason:"+e.getMessage());
 }

这样做会显示是否有任何 IO 异常抛出。

您也可以评论tempFile.delete(); 来检查文件是否真的有任何数据。如果您想一直删除它,请创建一个新的做

public static void main (String args[])  {
   //Declaring the file
   File tempFile = new File("D:\\myTempFile.txt");

   if(!tempFile.exists()){
       tempFile.createNewFile();
   }

编辑 2

这是一个工作示例

    public static void main(String[] args){               
        try{

           File tempFile = new File("c:/testing/temp.txt");
           tempFile.getParentFile().mkdirs();
           tempFile.createNewFile();

           writeToFile(tempFile);
           //readFromFile();
           //deleteFile();

        } catch(IOException ioe){
           ioe.printStackTrace();
        }
    }

    public static void writeToFile (File file) throws IOException{

        //Declaring the writer
        BufferedWriter writer = new BufferedWriter(new FileWriter(file));

        int n=0;
        int L=1;

        //Writing to the file if it did not exist
        while(n<15 && L<3) {
            n++;
            writer.write("L"+L+"0"+n);
            writer.newLine();
            L++;
            writer.write("L"+L+"0"+n);
            writer.newLine();
            L++;
            writer.write("L"+L+"0"+n);
            writer.newLine();
            L=1;
        }

        writer.close(); 
   }

【讨论】:

  • 在 isFile 之前尝试过,同样的问题出现
  • tempFile.isFile()==false,这里你说如果它不是一个文件然后写,所以删除它并做 if tempFile.exists()
  • 谢谢,我删除了 isFile 并改为使用了 exists(),仍然没有任何改变
  • 首先非常感谢您对我的容忍。所以我编辑了代码(编辑了if语句,删除了抛出IOException,更改了main和FreeParkingSpaces方法中的catch,将“tempFile”更改为“pLotsFile”)但问题仍然存在,我猜问题不在main方法?
  • 我根本不同意异常处理部分。如果main 抛出异常,则无论如何都会显示异常——您所做的只是使代码更复杂,并且如果抛出IOException 以外的任何内容,则隐藏堆栈跟踪。已经很好了。 OP 的真正问题是他们正在创建一个 FileWriter,它会立即创建文件 - 此时他们无法判断该文件是否存在 该语句之前。
猜你喜欢
  • 1970-01-01
  • 2014-09-14
  • 2022-12-08
  • 2019-04-17
  • 1970-01-01
  • 1970-01-01
  • 2017-09-25
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多