2016-10-16 1 views
0

글쎄요, 입/출력 파일을 만들려고합니다. 그래서 응용 프로그램을 시작할 때 파일을 읽고 올바른 위치에 정보를 넣습니다. 응용 프로그램에서이 파일에 정보를 추가 할 수 있습니다.파일에 이상한 것들을 읽거나 인쇄하십시오. Java

문제는 " 1"과 같은 정말 이상한 것을 읽고 씁니다. 이건 내 읽기 기능입니다 :

private Vector<GEPlayer> ReadPlayers() { 
    Vector<GEPlayer> play_aux = new Vector<>(); 
    String path = System.getProperty("user.dir"); 

    try { 
     File fread = new File(path + "/bin/Players.txt"); 
     System.out.println(fread.length()); 
     if (fread.length() > 3) { 
      BufferedReader bread = new BufferedReader(new InputStreamReader(new FileInputStream(fread), "ISO-8859-1")); 
      String linea; 
      int i = 0; 

      while ((linea = bread.readLine()) != null) { 
       GEPlayer p_aux = new GEPlayer(-1); 
       if (linea != null) { 
        switch (i) { 
         case 0: 
          currentidplayer = Integer.parseInt(linea); 
          p_aux.setId_player(currentidplayer); 
          System.out.println("GEModel -- ReadPlayers -- Readed Player ID: " + currentidplayer); 
          i++; 
          break; 
         case 1: 
          currentidteam = Integer.parseInt(linea); 
          p_aux.setId_team(currentidteam); 
          System.out.println("GEModel -- ReadPlayers -- Readed Player Team ID: " + currentidplayer); 
          i++; 
          break; 
         case 2: 
          p_aux.setName(linea); 
          System.out.println("GEModel -- ReadPlayers -- Readed Player Name: " + linea); 
          i++; 
          break; 
         case 3: 
          p_aux.setSurname(linea); 
          System.out.println("GEModel -- ReadPlayers -- Readed Player Surname: " + linea); 
          i++; 
          break; 
         case 4: 
          p_aux.setNacionality(linea); 
          System.out.println("GEModel -- ReadPlayers -- Readed Player Nacionality: " + linea); 
          i++; 
          break; 
         case 5: 
          p_aux.setActualTeam(linea); 
          System.out.println("GEModel -- ReadPlayers -- Readed Player Actual Team: " + linea); 
          i++; 
          break; 
         case 6: 
          p_aux.setBornDate(linea); 
          System.out.println("GEModel -- ReadPlayers -- Readed Player Born Date: " + linea); 
          i++; 
          break; 
         case 7: 
          p_aux.setNumber(Integer.parseInt(linea)); 
          System.out.println("GEModel -- ReadPlayers -- Readed Player Number: " + linea); 
          play_aux.add(p_aux); 
          i = 0; 
          break; 
        } 
       } 
      } 
      if (i != 0) { 
       currentidplayer = 0; 
       play_aux.removeAllElements(); 
      } 
     } 

    } catch (FileNotFoundException | UnsupportedEncodingException ex) { 
     Logger.getLogger(GEModel.class.getName()).log(Level.SEVERE, null, ex); 
    } catch (IOException ex) { 
     Logger.getLogger(GEModel.class.getName()).log(Level.SEVERE, null, ex); 
    } 

    return play_aux; 
} 

그리고 이것은 나의 쓰기 기능입니다 : 내가 TXT 정보 확인하지 않고 프로그램을 실행하면

private void writePlayer(GEPlayer aux) { 
    File fw; 
    BufferedWriter bw = null; 

    try { 
     String path = System.getProperty("user.dir"); 
     fw = new File(path + "/bin/Players.txt");   ///< The true will append the new data 
     FileOutputStream fos = new FileOutputStream(fw); 
     bw = new BufferedWriter(new OutputStreamWriter(fos)); 
     bw.write(aux.getId_player());       ///< Appends the string to the file 
     System.out.println("GEModel -- writePlayer -- Printed: " + aux.getId_player()); 
     bw.newLine(); 
     bw.write(aux.getId_team());        ///< Appends the string to the file 
     System.out.println("GEModel -- writePlayer -- Printed: " + aux.getId_team()); 
     bw.newLine(); 
     bw.write(aux.getName());        ///< Appends the string to the file 
     System.out.println("GEModel -- writePlayer -- Printed: " + aux.getName()); 
     bw.newLine(); 
     bw.write(aux.getSurname());        ///< Appends the string to the file 
     System.out.println("GEModel -- writePlayer -- Printed: " + aux.getSurname()); 
     bw.newLine(); 
     bw.write(aux.getNacionality());       ///< Appends the string to the file 
     System.out.println("GEModel -- writePlayer -- Printed: " + aux.getNacionality()); 
     bw.newLine(); 
     bw.write(aux.getActualTeam());       ///< Appends the string to the file 
     System.out.println("GEModel -- writePlayer -- Printed: " + aux.getActualTeam()); 
     bw.newLine(); 
     bw.write(aux.getBornDate());       ///< Appends the string to the file 
     System.out.println("GEModel -- writePlayer -- Printed: " + aux.getBornDate()); 
     bw.newLine(); 
     bw.write(aux.getNumber());        ///< Appends the string to the file 
     System.out.println("GEModel -- writePlayer -- Printed: " + aux.getNumber()); 
     bw.newLine(); 
     bw.close(); 
    } catch (IOException ex) { 
     Logger.getLogger(GEModel.class.getName()).log(Level.SEVERE, null, ex); 
    } finally { 
     try { 
      bw.close(); 
     } catch (IOException ex) { 
      Logger.getLogger(GEModel.class.getName()).log(Level.SEVERE, null, ex); 
     } 
    } 
} 

, 내가 완벽하게 모든 것을 읽을 수 있습니다, 그것은 올바른 정보를 보여줍니다 그 정보가 옳다고 나에게 말한다.

Exception in thread "main" java.lang.NumberFormatException: For input string: "1" 
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65) 
at java.lang.Integer.parseInt(Integer.java:580) 
at java.lang.Integer.parseInt(Integer.java:615) 
at GEModel.GEModel.ReadPlayers(GEModel.java:55) ///< This line is this: "currentidplayer = Integer.parseInt(linea);" 
at GEModel.GEModel.<init>(GEModel.java:34) 
at GEMain.GEMainClass.main(GEMainClass.java:22) 

자바 결과 : 나는 응용 프로그램을 다시 시작할 때, 그것은 나 같은 오류가 발생 한

나는이 문제를 해결하기 위해 무엇을 할 수 있는가?

+0

힌트 : 간단한 뭔가

시도 원칙 "추상화의 단일 계층"에 대해 읽어; 일반적으로 "깨끗한 코드"에 관한 것입니다. 가난한 방법으로 너무 많은 일을하고 있습니다. 그렇게하면 자신의 물건을 읽을 수 없게됩니다. 그것이 다른 사람들을 위해 있어야하는 것보다 훨씬 더 어렵습니다. – GhostCat

+0

다시 시작하십시오. 하나의 항목을 파일에 쓰고 해당 항목을 읽을 수 있는지 확인하십시오. 한 항목을 쓰고 읽는 데 성공하면 두 항목으로 이동하십시오. 모든 항목을 쓰고 읽을 때까지이 방법을 계속하십시오. 이렇게하면 작성한 항목을 읽는 데 문제가있을 때 코드에 추가 한 가장 최근 항목이 문제 일 가능성이 큽니다. –

+0

'GEPlayer '의 구현을 추가하십시오. – krzydyn

답변

0

이것은 사용자가 읽을 때 명시 적 인코딩을 설정하기 때문입니다. 그러나 쓰지 않을 때, 디폴트 값인 UTF-8이 사용됩니다.

글을 쓸 때나 읽을 때 (그리고 UTF-8이 최선의 선택 일 것입니다) 같은 텍스트 인코딩을 사용하십시오.

File f=new File("/tmp/test.txt"); 
    try (FileOutputStream fos=new FileOutputStream(f)){ 
     int id=1; 
     BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(fos,"UTF-8")); 
     bw.write(String.valueOf(id)); //write player id 
     bw.newLine(); 
     bw.close(); 
    } catch (Exception e) { 
     e.printStackTrace(); 
    } 

    try (FileInputStream fis=new FileInputStream(f)){ 
     BufferedReader br = new BufferedReader(new InputStreamReader(fis,"UTF-8")); 
     String idstr=br.readLine(); 
     System.out.printf("readstr: '%s'\n",idstr); 
     int id=Integer.parseInt(idstr);  // parse player id 
     System.out.printf("parse id: '%d'\n",id); 
     br.close(); 
    } catch (Exception e) { 
     e.printStackTrace(); 
    } 
+0

나는 그것을 시도해 보았습니다. 그러나 그것은 이상한 일들을 여전히 그리기 때문에 다른 일이 일어나는 것처럼 보입니다 ... –

+0

'aux.getId_player() '. 'bw.write'는'String'을 필요로합니다 – krzydyn

+0

고마워요! 제대로 작동하지 않지만 몇 가지 다른 문제가 해결되었습니다. 감사합니다! –

관련 문제