이 코드를 여러 번 실행하고 마침내 문제가 무엇인지 알아 내지 못했습니다. 매니페스트에서 읽기/쓰기 권한을 모두 사용하지만 마침내이 오류가 발생합니다. 안드로이드 스튜디오 프로젝트 :FileOutputStream을 사용할 때 .FileNotFoundException이 발생합니다.
11-13 20 : 35 : System.err에/W 03.097 3691-3691/ir.atiafar.files : java.io.FileNotFoundException/저장/에뮬레이트/0/MYDIR/k.txt : 개방 실패 : ENOENT (해당 파일 또는 디렉터리)
라인 (62)에 따르면 tv.setText (f.getCanonicalPat h());
public class MainActivity extends AppCompatActivity {
TextView input_fileName, input_content, tv;
Button btnWrite;
File extDir;
File dir;
String file_name, content ;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
input_fileName = (TextView) findViewById(R.id.edt_filename);
input_content = (TextView) findViewById(R.id.edt_content);
tv = (TextView) findViewById(R.id.tv);
btnWrite = (Button) findViewById(R.id.btn_writeFile);
extDir = Environment.getExternalStorageDirectory();
dir = new File(extDir, "mydir");
btnWrite.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
file_name = input_fileName.getText().toString().trim();
content = input_content.getText().toString();
if (!dir.exists())
dir.mkdirs();
file_name.replace(' ', '_');
if (!file_name.endsWith(".txt"))
file_name += ".txt";
File f = new File(dir, file_name);
try {
tv.setText(f.getCanonicalPath());
FileOutputStream fos = new FileOutputStream(f);
fos.write(content.getBytes());
fos.close();
Toast.makeText(MainActivity.this, "File Created!", Toast.LENGTH_SHORT).show();
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(MainActivity.this, "exception : " + e.getMessage(), Toast.LENGTH_LONG).show();
}
}
});
}
}
첫 번째 이후에 두 번째'! dir.exists()'검사를 시도하십시오 - 디렉토리가 생성되고 있는지 확인 하시겠습니까? 'FileOutputStream'은'mkdirs()'가 실패 할 경우 디렉토리를 생성하지 않습니다. –
또한'f'를 선언 한 후에'f.createNewFile();'을 시도하십시오. 파일이 이미 존재하면 아무것도하지 않습니다. –