2013-11-27 4 views
0

그래서 상징화 된 항목의 목록을 표시하고 사용자가 삭제할 항목을 선택하게하려고합니다.if 문은 출력을 공백으로 처리합니다.

  1. 나는 정보를 txt 파일에 씁니다.
  2. 파일의 내용을 배열에 저장합니다.
  3. 배열을 인쇄합니다.
  4. 사용자가 입력 한 내용 (예 : L101)은 파일 에서 삭제됩니다.

문제는 단계 (1)입니다. 파일이 존재하지 않는 경우에만 파일을 작성하고 싶습니다. 그래서 독자는 파일을 읽고 배열에 저장 할 수없는 것처럼,

if(file.isFile() ==false). 

이 그러나 빈 출력에 보인다과 함께 파일에 기록됩니다 while 루프 앞에. 왜? P.S 내가 if 및 else 문을 넣지 않으면 출력이 정상입니다. 파일을 다시 쓰는 것입니다. 나는 그런 일이 일어나기를 원하지 않습니다. 사용자가 입력 한 것을 제외한 모든 것을 보여주기를 바랍니다.

제발 제발 벌써 자바로 시작합니다. 그래서 나는 깊이 실수를 사과드립니다. 다음은 코드를

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!");} 
        } 
} 

답변

0

isFile() 검사의 경우 그 파일 (디렉토리가 아닌)

exists() 검사 파일이 존재합니다.

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

변경 그것. 또한 항상 방법에 대한 문서를 읽고 사용하기 전에 용도를 정확히 알아야합니다. 문 부울을 경우

참고, 그렇게 if(file.exists()){} 또는 if(file.isFile()){} 올바른 방법입니다

편집 :

당신은 여전히 ​​여기에 파일로 데이터를 가져 오는 문제를 당신이 무엇을해야하는지 갖는 때문에 .

먼저 IOException을 처리하십시오. throws IOException을 수행하면 기본적으로 상위 수준에서 예외를 처리 할 것이라고 말하지만 주 또한 예외를 선언하므로 예외가 발생하지 않습니다 (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(); 
    } 

편집이 여기

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(); 
    } 
+0

그것을 시도 동작하는 예제에도 ISFILE 전에, 동일한 작업을 수행 문제가 발생했습니다 – user3040333

+0

tempFile.isFile() == false, 파일이 아닌 경우 다음과 같이 쓰고 제거하십시오. tempFile.exists() –

+0

감사합니다. isFile을 제거하고 존재했습니다.) 대신에, 아직도 아무것도 바뀌지 않았다. – user3040333

관련 문제