2011-01-11 5 views
2

저는 전화 메모리에 텍스트 파일을 만들고 그 내용을 표시해야합니다. 이제 텍스트 파일을 만들었습니다. 그러나 data/data/package- name/file name.txt & 에뮬레이터의 내용을 표시하지 않았습니다.안드로이드의 전화 메모리에서 텍스트 파일을 읽습니다.

내 코드는 ... ADV에서

public class PhonememAct extends Activity { 
    /** Called when the activity is first created. */ 
    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     TextView tv=(TextView)findViewById(R.id.tv); 

     FileOutputStream fos = null; 
     try { 
      fos = openFileOutput("Test.txt", Context.MODE_PRIVATE); 
     } catch (FileNotFoundException e2) { 
      // TODO Auto-generated catch block 
      e2.printStackTrace(); 
     } 
     try { 
      fos.write("Hai..".getBytes()); 
     } catch (IOException e1) { 
      // TODO Auto-generated catch block 
      e1.printStackTrace(); 
     } 
     try { 
      fos.close(); 
     } catch (IOException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } 


     FileInputStream fis = null; 
     try { 
      fis = openFileInput("Test.txt"); 
     } catch (FileNotFoundException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } 
     int c; 

     try { 
      while((c=fis.read())!=-1) 
        { 
         tv.setText(c); 
         setContentView(tv); 

         //k += (char)c; 
        } 
     } catch (IOException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } 

      try { 
       fis.close(); 
      } catch (IOException e) { 
       // TODO Auto-generated catch block 
       e.printStackTrace(); 
      } 


    } 
} 

감사합니다.

+0

. } – Beasly

답변

6

단순히 텍스트를 쓰거나 읽으려는 경우 입력/출력 스트림을 사용할 필요가 없습니다.

FileWriter를 사용하여 텍스트를 파일에 쓰고 BufferedReader를 사용하여 파일에서 텍스트를 읽습니다. 훨씬 간단합니다. 이것은 또한 하나 개의 try 블록을 넣어 다른 예외를 잡을 수 ... 완벽하게 작동

try { 
    File myDir = new File(getFilesDir().getAbsolutePath()); 
    String s = ""; 

    FileWriter fw = new FileWriter(myDir + "/Test.txt"); 
    fw.write("Hello World"); 
    fw.close(); 

    BufferedReader br = new BufferedReader(new FileReader(myDir + "/Test.txt")); 
    s = br.readLine(); 

    // Set TextView text here using tv.setText(s); 

} catch (FileNotFoundException e) { 
    e.printStackTrace(); 
} catch (IOException e) { 
    e.printStackTrace(); 

}

+0

나는 당신의 example.Text 파일을 사용해 보았습니다. 그러나 프로그램을 실행하려고하면 "프로세스가 예기치 않게 중지되었습니다. ". 내 로그캣이 말했습니다 .011-11 14 : 24 : 05.253 : ERROR/AndroidRuntime (25814) : 잡히지 않은 핸들러 : 캐치되지 않은 예외로 인해 스레드 메인이 종료 됨 01-11 14 : 24 : 05.263 : ERROR/AndroidRuntime (25814) : – sanjay

+0

@ Sudhakar : 나는 당신이 "setContentView (tv);"를 사용할 수 없다는 것을 언급했다. 그런 식으로. TextView가 포함 된 main.xml과 같은 XML 레이아웃 파일이 있어야하며 "setContentView (R.layout.main);"을 호출해야합니다. "super.onCreate (savedInstanceState)"를 호출 한 직후에 콘텐츠보기를 'TV'로 설정하지 마십시오. – Squonk

+0

좋아! 마침내 찾았 어. 스컹크 고마워. – sanjay

0

귀하의 질문에 대한 답변이 아닐 수도 있습니다.
나는 try-catch를 올바르게 사용해야한다고 생각한다. openFileInput() 호출이 실패하고 null 객체에 fos.write()fos.close()이 호출된다고 상상해보십시오.

fis.read()fis.close()에서 같은 것을 볼 수 있습니다.

하나의 단일 try-catch 블록에 openFileInput(), fos.write()fos.close()을 포함시켜야합니다. 'fis'에도 유사한 변경이 필요합니다.

먼저 시도해보십시오!

+0

답장을 보내 주셔서 감사합니다. 나는 시도 할 것입니다 .. – sanjay

0

스트림으로 시도해 볼 수 있습니다.

public static void persistAll(Context ctx, List<myObject> myObjects) { 

    // save data to file 
    FileOutputStream out = null; 

    try { 
      out = ctx.openFileOutput("file.obj", 

      Context.MODE_PRIVATE); 
      ObjectOutputStream objOut = new ObjectOutputStream(out); 
      objOut.writeObject(myObjects); 
      } catch (Exception e) { 
     e.printStackTrace(); 
      } finally { 
      try { 
       out.close(); 
      } catch (IOException e) { 
       e.printStackTrace(); 
      } 
     } 
    } 

이렇게 잘되어 가고 있습니다. 텍스트로 저장하는 것은 그다지 다르지는 않지만 직장에서 테스트 할 Java IDE가 없습니다. 희망이 도움이됩니다!

1
//Find the directory for the SD Card using the API 
    //*Don't* hardcode "/sdcard" 
    File sdcard = Environment.getExternalStorageDirectory(); 

    //Get the text file 
    File file = new File(sdcard,"file.txt"); 

    //Read text from file 
    StringBuilder text = new StringBuilder(); 

    try { 
    BufferedReader br = new BufferedReader(new FileReader(file)); 
    String line; 

    while ((line = br.readLine()) != null) { 
    text.append(line); 
    text.append('\n'); 
    } 
    } 
    catch (IOException e) { 
    //You'll need to add proper error handling here 
    } 

    //Find the view by its id 
    TextView tv = (TextView)findViewById(R.id.text_view); 

    //Set the text 
    tv.setText(text); 
1
//To read file from internal phone memory 
//get your application context: 
Context context = getApplicationContext(); 

filePath = context.getFilesDir().getAbsolutePath(); 
File file = new File(filePath, fileName); 
StringBuilder text = new StringBuilder(); 

try { 
    BufferedReader br = new BufferedReader(new FileReader(file)); 
    while ((line = br.readLine()) != null) { 
     text.append(line); 
     text.append('\n'); 
    } 
} 
catch (IOException e) { 

} 
return text.toString(); //the output text from file. 
관련 문제