2012-10-31 2 views
15

안드로이드를 처음 사용하며 파일을 내부 저장소에 저장하려고 할 때 문제가 발생합니다. 새 예제는 내 SDK에서 작동하지만 작동하지 않습니다. 내 휴대 전화.내부 저장소에 파일 저장 안드로이드

/data/data/com.example.key/files/text/(my_title) 

감사합니다 : - 나는 그런데 안드로이드 2.1, 소니 에릭슨의 XPERIA 예를 드 실행하기 위해 노력하고있어

합니다 ... log.i 나에게 다음 라인을 제공합니다. 내 안드로이드 manifiest에서

@Override 
     protected void onCreate(Bundle savedInstanceState) { 
      // TODO Auto-generated method stub 
      super.onCreate(savedInstanceState); 

      setContentView(R.layout.new_text); 

      file = (EditText) findViewById(R.id.title_new); 
      entry = (EditText) findViewById(R.id.entry_new); 

      btn = (Button) findViewById(R.id.save_new); 
      btn.setOnClickListener(new OnClickListener() { 

       @Override 
       public void onClick(View v) { 

        File myDir = getFilesDir(); 


        NEWFILENAME = file.getText().toString(); 
        if (NEWFILENAME.contentEquals("")){ 
         NEWFILENAME = "UNTITLED"; 
        } 
        NEWENTRY = entry.getText().toString(); 

        try { 

         File file_new = new File(myDir+"/text/", NEWFILENAME); 
         file_new.createNewFile(); 

         Log.i("file", file_new.toString()); 

         if (file_new.mkdirs()) { 
          FileOutputStream fos = new FileOutputStream(file_new); 

          fos.write(NEWENTRY.getBytes()); 
          fos.flush(); 
          fos.close(); 
         } 

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

        Intent textPass = new Intent("com.example.TEXTMENU"); 
        startActivity(textPass); 
       } 
      }); 

      } 


//That's for creating... then in other activity i'm reading 

      @Override 
     protected void onCreate(Bundle savedInstanceState) { 
      // TODO Auto-generated method stub 
      super.onCreate(savedInstanceState); 
      setContentView(R.layout.text_menu); 

      btn = (Button) findViewById(R.id.newNote); 
      listfinal = (ListView) findViewById(R.id.listView); 

      btn.setOnClickListener(new OnClickListener() { 

       @Override 
       public void onClick(View v) { 
        // TODO Auto-generated method stub 
        Intent textPass = new Intent("com.example.TEXTNEW"); 
        startActivity(textPass); 

       } 
      }); 

      listfinal.setOnItemClickListener(this); 

      File fileWithinMyDir = getApplicationContext().getFilesDir(); 


      loadbtn = (Button) findViewById(R.id.loadList); 

      loadbtn.setOnClickListener(new OnClickListener() { 

       @Override 
       public void onClick(View v) { 
        File myDir = getFilesDir(); 

        File dir = new File(myDir + "/text/"); 

        String[] files = dir.list(); 

        //String[] files = getApplicationContext().fileList(); 
        List<String> list = new ArrayList<String>(); 

        for (int i =0; i < files.length; i++){ 
         list.add(files[i]); 
        } 
        ArrayAdapter<String> ad = new ArrayAdapter<String>(TextMenu.this, android.R.layout.simple_list_item_1, 
            android.R.id.text1, list); 

        listfinal.setAdapter(ad); 
       } 
      }); 
      } 

내가

   <uses-sdk 
        android:minSdkVersion="5" 
        android:targetSdkVersion="15" /> 

       <uses-permission android:name="android.hardware.camera" /> 
       <uses-permission android:name="android.permission.INTERNET" /> 
       <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> 
       <uses-permission android:name="android.permission.WRITE_INTERNAL_STORAGE" /> 
+0

LogCat을 제공 할 수 있습니까? – 323go

+1

'File.mkdirs()'로 먼저 파일을 놓을 디렉토리를 만드십시오. – vasart

답변

27

난 당신이 언급되는 예를 너무 확실하지 않다 그러나 나는있는 그들 중 적어도 하나에 맞게해야 여기에 두 개의 작업 샘플을 가지고있는 권한이 너의 요구. 는 I는 X10 주행 빌드 번호 2.1.A.0.435 번 페리아 T 주행 빌드 번호 7.0.A.1.303 한 넥서스 S 주행 빌드 번호 JZO54K

예 1

String filename = "myfile"; 
    String outputString = "Hello world!"; 

    try { 
     FileOutputStream outputStream = openFileOutput(filename, Context.MODE_PRIVATE); 
     outputStream.write(outputString.getBytes()); 
     outputStream.close(); 
    } catch (Exception e) { 
     e.printStackTrace(); 
    } 

    try { 
     FileInputStream inputStream = openFileInput(filename); 
     BufferedReader r = new BufferedReader(new InputStreamReader(inputStream)); 
     StringBuilder total = new StringBuilder(); 
     String line; 
     while ((line = r.readLine()) != null) { 
      total.append(line); 
     } 
     r.close(); 
     inputStream.close(); 
     Log.d("File", "File contents: " + total); 
    } catch (Exception e) { 
     e.printStackTrace(); 
    } 

예 2에서 이러한 테스트

String filename = "mysecondfile"; 
    String outputString = "Hello world!"; 
    File myDir = getFilesDir(); 

    try { 
     File secondFile = new File(myDir + "/text/", filename); 
     if (secondFile.getParentFile().mkdirs()) { 
      secondFile.createNewFile(); 
      FileOutputStream fos = new FileOutputStream(secondFile); 

      fos.write(outputString.getBytes()); 
      fos.flush(); 
      fos.close(); 
     } 
    } catch (Exception e) { 
     e.printStackTrace(); 
    } 

    try { 
     File secondInputFile = new File(myDir + "/text/", filename); 
     InputStream secondInputStream = new BufferedInputStream(new FileInputStream(secondInputFile)); 
     BufferedReader r = new BufferedReader(new InputStreamReader(secondInputStream)); 
     StringBuilder total = new StringBuilder(); 
     String line; 
     while ((line = r.readLine()) != null) { 
      total.append(line); 
     } 
     r.close(); 
     secondInputStream.close(); 
     Log.d("File", "File contents: " + total); 
    } catch (Exception e) { 
     e.printStackTrace(); 
    } 
+0

왜'secondFile.getParentFile(). mkdirs()'체크가 설명해 주시겠습니까? – yashhy

+3

대답에 여전히 관심이 있다면이 호출은 파일 경로가 존재하는지 확인하기 위해 필요한 경우 디렉토리 계층 구조를 생성합니다. – prom85

+0

누군가이 답변에 여전히 관심이있는 경우 : WRITE_EXTERNAL_STORAGE 권한은 런타임에 요청되어야합니다. 그렇지 않으면 "권한이 거부되었습니다."라는 오류 메시지가 나타납니다. – Zoe

1

매니페스트 파일에 읽기 및 쓰기 권한을 부여했지만 삼성 Galaxy S7에 "Permission denied"문제가 발생했습니다. 나는 전화 설정 >> 응용 프로그램 >> [내 응용 프로그램]으로 가서 그것을 해결하고 허가하에 "스토리지"를 허용했습니다. 그 후 잘 일했다.

+2

** Pitfall : ** 앱이 API 23 이상을 타겟팅하는 경우 런타임에 쓰기 외부 저장소 권한을 요청해야합니다. WRITE_EXTERNAL_STORAGE는 위험한 권한이므로 요청해야합니다. – Zoe

관련 문제