2012-11-02 9 views
1

이 파일은 크랙 할 수있는 간단한 파일 일 수 있지만이 코드가 Android 외장 파일 시스템에 새 파일을 생성하지 않는 이유는 무엇인지 알 수 없습니까? 디렉토리가 올바르게 생성되었지만 파일이 아니라 java.io.FileNotFoundException을 얻습니다./mnt/sdcard/Mydir/MyFile, 아무도 내가 눈을 뜰 수없는 원인을 볼 수 있습니까?외부 저장소에 파일을 만들고 저장하십시오.

답변

0

을 시도 ...
 //Generate a unique filename using date and time 
    String fileName = "myFile_"+formatter_file_name.format(today)+".txt"; 

    //Get path to root 
    String root = Environment.getExternalStorageDirectory().toString(); 

    //Create(if not exists) directory in root in which to store the reports 
    File myDir = new File(root + "/myDir"); 
    myDir.mkdirs(); 

    //Create report file object 
    File file = new File (myDir, fileName); 

    //If file already exists delete id(this should not be able to happen) 
    if (file.exists()) file.delete(); 

    try { 
     FileOutputStream fout = new FileOutputStream(file); 
     OutputStreamWriter osw = new OutputStreamWriter(fout); 

     // Write the string to the file 
     osw.write("TEST STRING"); 

     //Ensure that everything has been written to the file and close 
     osw.flush(); 
     osw.close(); 
    } catch (Exception e) { 
      e.printStackTrace(); 
    }  

나는 나의 매니페스트에 올바른 사용 권한이, 그리고 외부 스토리지를 쓰기 위해 사용할 수 있는지 확인하기 위해 검사를 삽입합니다하지만 난 그게 문제라고 생각하지 말자
try { 
    File root = Environment.getExternalStorageDirectory(); 
    File myFile = new File(root +"/textfile.txt"); 
    myFile.createNewFile(); 

    FileOutputStream fOut = new FileOutputStream(myFile); 
    OutputStreamWriter myOutWriter = 
     new OutputStreamWriter(fOut); 
    myOutWriter.append("String entered in file"); 

    myOutWriter.close(); 
    fOut.close(); 
} catch (Exception e) { 
    Toast.makeText(getBaseContext(), e.getMessage(),Toast.LENGTH_SHORT).show(); 

} 
+0

오키,이 대답을보고 도움이되는지 확인하겠습니다. 하지만 왜 그것이 downvoted되었습니다 ?? – Robert

+0

나는 또한 이것이 왜 downvoted인지 알지 못했다. 나는이 작업을하고 있습니다., http://hoodaandroid.blogspot.in/2012/07/reading-and-writing-data-to-sdcard.html을 읽고 읽고 쓸 수있는 모든 정보를 얻을 수 있습니다. .. –

+0

지금 코드를 테스트 해 보니 매력적으로 작동합니다. 내 코드에 두 가지 문제가 있었는데, 먼저이 메서드를 myFile.createNewFile()이라고 부르지 않았으므로 FileNotFound 예외가 발생합니다. 두 번째 내 파일 이름에 유효하지 않은 문자 (:)가 포함되어있어 FileException (잘못된 인수)이 표시됩니다. 그것은 단순한 실수였습니다 ;-) 나는 당신의 해결책에 투표했습니다. – Robert

관련 문제