2015-01-27 3 views
0

손을주세요.안드로이드 내부 저장 장치에 파일을 쓸 수 없습니다

Android 내부 저장소의 파일 텍스트에 내용을 쓰려고합니다.

다음과 같은 스트림 메소드를 사용하고 있습니다. 그건 그렇고, 쓰지 않습니다.

해결해 주시겠습니까? 당신이 scrivi() 방법 내부 data를 사용하지 않는 때문에

public class MainActivity extends ActionBarActivity { 

    File f=new File("box"); 
    public void scrivi(String data) 
    {try { 

     FileOutputStream fos = new FileOutputStream(f); 
     PrintWriter pw = new PrintWriter(fos); 
     pw.write(""); 
    } 
    catch(FileNotFoundException e){ 
     Toast t = Toast.makeText(this, ("Il FILE NON ESITE"), Toast.LENGTH_LONG); 
     t.show(); 

    } 
    } 

    public void read(String word) 
    {try{ 
     FileInputStream fis = new FileInputStream(f); 
     BufferedReader br = new BufferedReader(new InputStreamReader(fis)); 
     String line=""; 
     while((line=br.readLine())!=null); 
     println(line); 
    } 

    catch(FileNotFoundException n){Toast x = Toast.makeText(this, ("Il FILE NON SI PUO' LEGGERE"), Toast.LENGTH_LONG); 
     x.show();} 
     catch(IOException w){{Toast q = Toast.makeText(this, ("c'e' un problema"), Toast.LENGTH_LONG); 
      q.show();}} 
    } 
    @Override 
    protected void onCreate(Bundle savedInstanceState){ 
      super.onCreate(savedInstanceState); 
      setContentView(R.layout.activity_main); 

      ArrayList lista = new ArrayList(); 
      Intent j = getIntent(); 
      String nome = j.getStringExtra("nome"); 
      lista.add(nome); 
      scrivi(nome); 








     if(nome!=null) 

    { 

     Toast toast = Toast.makeText(this, ("ciao " + " " + nome), Toast.LENGTH_LONG); 
     toast.show(); 
    }} 







    public void go(View v){ 
     Intent intent=new Intent(this,SecondActivity.class); 
     startActivity(intent); 


    } 
    public void time(View c){ 
     Intent i=new Intent(this,ActivityPicker.class); 
     startActivity(i); 
    } 

    public void pass(View p){ 
     EditText nome6=(EditText)findViewById(R.id.nome6); 
     String inviaDati = nome6.getText().toString(); 
     read(inviaDati); 
    } 


    @Override 
    public boolean onCreateOptionsMenu(Menu menu) { 
     // Inflate the menu; this adds items to the action bar if it is present. 
     getMenuInflater().inflate(R.menu.menu_main, menu); 
     return true; 
    } 

    @Override 
    public boolean onOptionsItemSelected(MenuItem item) { 
     // Handle action bar item clicks here. The action bar will 
     // automatically handle clicks on the Home/Up button, so long 
     // as you specify a parent activity in AndroidManifest.xml. 
     int id = item.getItemId(); 

     //noinspection SimplifiableIfStatement 
     if (id == R.id.action_settings) { 
      return true; 
     } 

     return super.onOptionsItemSelected(item); 
    } 
} 
+0

으악. 좋은 캐치. 질문을 잘못 읽습니다. 감사합니다 – Willis

답변

0

이 있습니다. 이것으로 시도 : 보조 노트로

public void scrivi(String data, Context ctx){ 
    try { 
     FileOutputStream fos = ctx.openFileOutput(); 
     PrintWriter pw = new PrintWriter(fos); 
     pw.write(data); 
    } 
    catch(FileNotFoundException e){ 
     Log.e("ERR", e.getMessage(); 
    } 
} 

, 활동 컨텍스트 외부에서 호출하면 예상대로 작동하지 않을 수 있습니다으로 내가 내 "비즈니스"방법에 토스트를 사용하지 않는 것이 좋습니다. 오류를 추적하려면, 단지 열려고 할 것인가 Log.warn/정보/디버그

1
File f=new File("box"); 
FileOutputStream fos = new FileOutputStream(f); 

을 사용하고 교체 할 경우 필요한 경우 안드로이드

에 쓸 수없는 현재 작업 디렉토리 에서 파일을 생성 new fileOutputStream(f)openFileOutput(f)이 Activity 또는 다른 유효한 컨텍스트의 인스턴스 내에서 또는 그 인스턴스에서 호출되면 제목에 의해 제안 된대로 앱의 내부 저장소에 파일을 가져옵니다.

openFileInput(f)은 판독면에서 사용할 수 있습니다. 또한이 위치를 명시 적으로 사용하려면 getFilesDir()의 경로로이 위치를 얻을 수 있습니다.

비어있는 것을 작성하고 세부 사항을 위해 Toast보다는 Logging을 사용하는 Shine의 권장 사항 또한 중요합니다.

출력 스트림이 포함 된 메서드의 끝 뒤에서 가비지 수집시 예상되는 출력 스트림을 기다리지 않고 명시 적으로 닫는 것이 좋습니다.

+0

좋은 답변! openFileOutput()에 대해서는 생각하지 않았습니다. 가장 좋은 해결책은 컨텍스트를 전달하는 것이고, 힌트를 얻으려면 먼저 – Shine

+0

을 제안해야합니다. –

+0

당신이 이해할 수있는 것처럼 @Shine 나는 초보자이며, 나는 컨텍스트 개념을 분명히하지 못했다고 고백합니다. 설명을위한 링크를 제안 해 주시겠습니까? 어떻게 코드를 수정할 수 있습니까? –

관련 문제