2013-04-14 1 views
0

일부 사용자 자격 증명이 작성된 파일을 읽으려고합니다. 내부 저장소 위치에 파일을 쓰려고합니다. 코드 :방금 ​​작성한 파일을 읽을 수 없습니다.

private void writeSendDetails(String name, String number, String emailID) { 

     //This function writes details to userCredentials.txt and also sends it to server. 
     String text = "Name: " + userName + "\n" + "Number: " + userNumber + "\n" + "Email ID:" + userEmailID; 
     FileOutputStream fos = null; 
     try { 
      fos = openFileOutput(userCredFile, MODE_PRIVATE); 
      Log.v(this.toString(), fos.toString()); 
     } catch (FileNotFoundException e1) { 
      // TODO Auto-generated catch block 
      e1.printStackTrace(); 
     } 

     if(fos != null) { 
      OutputStreamWriter osw = new OutputStreamWriter(fos); 
      try { 
       osw.write(text); 
      } catch (IOException e) { 
       // TODO Auto-generated catch block 
       Log.v(this.toString(), "IOException caught in osw.write"); 
       e.printStackTrace(); 
      } 
      try { 
       osw.flush(); 
      } catch (IOException e) { 
       // TODO Auto-generated catch block 
       e.printStackTrace(); 
      } 
      try { 
       osw.close(); 
      } catch (IOException e) { 
       // TODO Auto-generated catch block 
       e.printStackTrace(); 
      } 
     } 

     Log.v(this.toString(), "Written everything to userCredentials.txt"); 
     readUserCredentials(); 
     //code to send to server should begin here. 

    } 

private void readUserCredentials() { 
     //function to read name, number and email ID from userCredentials.txt 
     /* Steps: 
     * 1. Check if file exists. 
     * 2. If it does, read all relevant credentials. 
     */ 

     File f = new File(userCredFile); 
     if(f.canRead()) { 
      Log.v(this.toString(), "Can open userCredentials for reading from."); 
     } 

     try { 
      FileReader fis = new FileReader(f); 
      Log.v(this.toString(), "Wrapping a buffered reader around file reader."); 
      BufferedReader bufRead = new BufferedReader(fis, 100); 
      String line; 
      try { 
       while((line = bufRead.readLine()) != null) { 
        Log.v(this.toString(), "Line read = " + line); 
        line = bufRead.readLine(); 
        if(line.indexOf("Name: ") != -1) { 
         Log.v(this.toString(), "Found name in the string."); 
         userName = line.substring(6); 
        } else if(line.indexOf("Number: ") != -1) { 
         Log.v(this.toString(), "Found number in the string."); 
         userNumber = line.substring(8); 
        } else if(line.indexOf("Email ID: ") != -1) { 
         Log.v(this.toString(), "Found email in the string."); 
         userEmailID = line.substring(10); 
        } 
       } 
       Log.v(this.toString(), "User credentials = " + userName + " " + userNumber + " " + userEmailID); 
      } catch (IOException e) { 
       Log.v(this.toString(), "IOException caught."); 
      } 
     } catch (FileNotFoundException e1) { 
      Log.v(this.toString(), "File not found for reading."); 
     } 
    } 

LogCat 출력을 보여줍니다

04-14 15:20:43.789: V/[email protected](675): Written everything to userCredentials.txt 
04-14 15:20:43.789: V/[email protected](675): File not found for reading. 
04-14 15:20:43.889: V/[email protected](675): File not found for reading. 

내 질문 (들) :
1. 나는 내부 저장 장치에 파일을 작성해야합니다. 내가 제대로하고 있니?
2. 방금 쓴 파일을 읽지 못하는 이유는 무엇입니까? 코드에 대한

+1

당신은 이러한 것들을 많이 가지고 있습니다 :'printStackTrace()'는 실제 오류를 숨길 수 있으며,'Log.e()'는이 오류들로 인해 파일이 실제로 기록되고 있는지를 알 수 있습니다. 내 추측은 쓰기 도중 발견되지 않습니다. – Oren

+1

'printStackTrace()'는 Eclipse가 생성하는 자동 구현 스텁의 일부입니다. – Sriram

+0

쓰기에 예외가 발생하지 않습니다. – Sriram

답변

1

어떤 것들은 :

  1. @Oren이 올바른지, 당신은 일식에서 대신 자동 생성 된 물건의 Log.e(TAG, "message", e)을 사용한다!
  2. 3 개의 try/catch를 하나로 병합하면됩니다. 필요도 당신의 FileNotFoundException에 대해 위에서 말했듯이 당신이 Log.e()를 사용한다 그것은 3 번 ...
  3. 하지 않습니다, 그래서
(현재 문제를 해결하기 위해 힌트를 포함하는) 진짜 이유를 확인하기 위해 스택 트레이스를 볼 수 있습니다

숫자 3 이상을 읽었다면 읽으려는 파일을 찾을 수 없다는 것을 알았을 것입니다. 로그에 if 문에서 나온 Can open userCredentials for reading from. 출력이 표시되지 않는 이유는 무엇입니까?

그 이유는 매우 간단합니다. openFileOutput(userCredFile, MODE_PRIVATE);을 사용하여 파일을 만듭니다. documentation of openFileOutput을 읽으면 다음과 같은 비틀 거리다.

열 파일의 이름. 경로 분리자를 포함 할 수 없습니다.

즉, userCredFiletest.txt과 같을 수 있습니다. 또한이 방법은 "외부"에서 쉽게 액세스 할 수없는 디렉토리에 파일을 만듭니다.

FileReader(userCredFile)을 통해 파일을 읽으려고하면 안드로이드가 루트 디렉토리 (/text.txt)에서 열려고 시도하고 분명히 실패합니다. 루트가 아닌 앱은 루트 디렉토리에 쓰거나 읽을 수 없습니다.

주요 질문 및 문제에 대한 답변 : 해당 openFileInput(userCredFile) 메서드를 사용하여 파일을 읽지 않는 이유는 무엇입니까?

관련 문제