una instrucción if deja en blanco la salida
Frecuentes
Visto 115 veces
0
I am trying to show a list of symbolized items and letting the user choose one to be deleted.
- I write the info to a txt file.
- I store the contents of the file in an array.
- I print out the array.
- The user inputs (L101 for example) and it will get deleted from the file.
The problem is in step (1) I want the file to be written, if and only if the file didn't exist. so I precede the while loop which will write to the file with
if(file.isFile() ==false).
This however seems to blank the output, as if the reader isn't able to read the file and store it in the array. why? P.S if I don't put an if and else statements the output is ok, it's just that it writes the file again, which I don't want to happen, I want ti to show everything except what the user typed.
Aqui esta el codigo
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!");}
}
}
1 Respuestas
0
isFile()
checks if its a file (not a directory)
exists()
checks if the file exists.
http://docs.oracle.com/javase/7/docs/api/java/io/File.html
Change it. Also, always make sure you read the docs about the method and know exactly its purpose before using it.
Note, if statements take a boolean, so if(file.exists()){}
or if(file.isFile()){}
es la forma correcta
Edit:
Since you are still having problems getting the data into the file here is what you should do.
Primero, maneje el IOException
. Cuando tu lo hagas throws IOException
you are, basically, saying that you will handle the exception at a higher level, but main also declares that, so the exception is never caught (One of the problems when learning using an IDE and auto-corrections).
To make that happen you need to do:
1) Eliminar todo throws IOException
2) Change the catch to be
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());
}
Doing this will show if there are any IO exceptions thrown.
You can also comment tempFile.delete();
to inspect if the file actually has any data. If you want to delete it all the time an create a new one do
public static void main (String args[]) {
//Declaring the file
File tempFile = new File("D:\\myTempFile.txt");
if(!tempFile.exists()){
tempFile.createNewFile();
}
Editar 2
Aquí hay un ejemplo de trabajo.
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();
}
respondido 27 nov., 13:08
Tried it even before isFile ,Same problem occurs - user3040333
tempFile.isFile()==false, here you are saying if it is not a file then write, so remove it and do if tempFile.exists() - Manchar
thanks, I removed isFile and did exists() instead, still nothing changed - user3040333
first thank you so much for putting up with me. so I edited the code (edited the if statement, deleted throws IOException, changed the catch in both the main and FreeParkingSpaces methods,changed "tempFile" to "pLotsFile") But the problem persists, I ma guessing the problem is not in the main method? - user3040333
I fundamentally disagree with the exception handling part. If main
throws an exception, the exception is displayed anyway - all you've done is made the code more complicated and hidden the stack trace if anything other than an IOException
is thrown. It was fine already. The OP's real problem is that they're creating a FileWriter
, which creates the file immediately - at which point they can't tell whether the file existed antes that statement or not. - jon skeet
No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas java arrays while-loop filereader or haz tu propia pregunta.
Welcome to Stack Overflow. You've posted over a hundred lines of code - and it's formatted in a way which is really hard to read. Could you try to reduce this to a mínimo example that still demonstrates the problem, then format it clearly, and edit that into the question? - Jon Skeet