Create textfile via FileOutputStream on external SD card in Android - FileNotFoundException

377 views Asked by At

I want to create a simple textfile on an Android device on external SD card. With my code, i always get the error: java.io.FileNotFoundException: /storage/emulated/0/SFX/TEST1.txt: open failed: ENOENT (No such file or directory)

i have set <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/> in my manifest file

        Button btn = (Button)findViewById(R.id.btn_Save);
        btn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            //mach was
            StringBuilder sb = new StringBuilder();
            sb.append(txtName.getText().toString());
            sb.append(System.getProperty("line.separator"));
            sb.append(txtMonteur.getText().toString());
            sb.append(System.getProperty("line.separator"));
            sb.append(txtStraße.getText().toString());
            sb.append(System.getProperty("line.separator"));
            sb.append(Energiearten);

            File file;
            FileOutputStream out;
            try
            {
                file = new File(Environment.getExternalStorageDirectory(), "SFX/TEST1.txt");
                file.mkdirs();
                out = new FileOutputStream(file);
                out.write(sb.toString().getBytes());
                out.close();

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

            } catch (Exception e) {
                Toast.makeText(ZBewegung.this, "Error:" + e.toString(), Toast.LENGTH_LONG).show();
            }
        }
    });
1

There are 1 answers

2
CommonsWare On
file = new File(Environment.getExternalStorageDirectory(), "SFX/TEST1.txt");
file.mkdirs();

This creates a directory named SFX/TEST1.txt, which is not what you want.

Try:

File dir=new File(Environment.getExternalStorageDirectory(), "SFX");
dir.mkdirs();
file = new File(dir, "SFX/TEST1.txt");