Carpeta creada en la tarjeta sd de Android, pero archivo no creado

I think I have looked at all of the relevant questions and I still can't get this to work.

Aquí está el código:

File sdCard = Environment.getExternalStorageDirectory();  
File directory= new File (sdCard.getAbsolutePath() + appName);          
directory.mkdirs();     
File file = new File(directory,fileName);  

The folder is created, but I get an error saying the file does not exist. appName is a string containing the name of the folder and that works correctly. fileName is a string containing the name of the file I want to include.

I have included the permission in the manifest.

¿Qué estoy haciendo mal?

Actualizar:

The code tries to make a subdirectory and a file at the same time, which hidden because the code uses a named String rather than a String literal. Adding an intermediate step to create the subdirectory solved the problem.

preguntado el 09 de marzo de 12 a las 15:03

If you work from windows add two // instead of one for Aleks G answer! -

Eclipse is on Windows, but I am debugging on my phone. A single / should do -- right? -

Try with something like this instead: File f = new File(Environment.getExternalStorageDirectory() + File.separator + "appName"); f.createNewFile(); I think the File.separator makes the difference! -

I Put full code as answer!here is difficult to see! -

3 Respuestas

If the directory is created, then you're on the right track. In your code you are not actually creating the file on the SD card. If you need to create the file, then do this:

File sdCard = Environment.getExternalStorageDirectory();  
File file = new File(sdCard.getAbsolutePath() + appName + "/" + fileName);
directory.mkdirs();
file.createNewFile()

This is notional only. It would be much better to actually separate your fileName into a separate subfolder and the actual file and handle them separately.

respondido 09 mar '12, 16:03

Thanks for answering. I added the line of code and I still get these exceptions. 03-09 09:56:42.697: W/System.err(31125): java.io.IOException: No such file or directory 03-09 09:56:42.707: W/System.err(31125): at java.io.File.createNewFileImpl(Native Method) - rooware

@user1244332 What are your values for appName and filename? Also what does sdCard.getAbsolutePath() return? - aleks g

appName = "/JoesHouse". fileName ="default/text.txt". sdCard.getAbsolutePath() returns /mnt/sdcard. directory.getAbsolutePath() returns /mnt/sdcard/JoesHouse. - rooware

Just out of curiosity, I tried adding a file to the folder with Quickoffice and it worked successfully, so the folder can be written to. - rooware

@user1244332 Well, your "filename" contains another directory name - and that directory doesn't exist. I've updated my answer to show how you should do what you need. - aleks g

Probar esto:

In this I am creating a text file (.txt file) of a string.

public void createFileFromString(String text)
    {       
       File logFile = new File("sdcard/xmlresponseiphone.txt");
       if (!logFile.exists())
       {
          try
          {
             logFile.createNewFile();
          } 
          catch (IOException e)
          {
             // TODO Auto-generated catch block
             e.printStackTrace();
          }
       }
       try
       {
          //BufferedWriter for performance, true to set append to file flag
          BufferedWriter buf = new BufferedWriter(new FileWriter(logFile, true)); 
          buf.append(text);
          buf.newLine();
          buf.close();
       }
       catch (IOException e)
       {
          // TODO Auto-generated catch block
          e.printStackTrace();
       }
    }

Test this, and see what are you missing :)

respondido 09 mar '12, 15:03

Thank you. I was trying to create a directory in the process of creating a file. I am very new to java IO - rooware

Try with something like this. In this case I'm saving an image!

For creating the directory:

File directory = new File(Environment.getExternalStorageDirectory()
                + File.separator + appName);
        directory.mkdirs();

And for saving into it public void save(Bitmap graph, Context context, String name, String time, boolean now) throws IOException {

    ByteArrayOutputStream bytes = new ByteArrayOutputStream();
    graph.compress(Bitmap.CompressFormat.PNG, 100, bytes);

    // you can create a new file name "test.jpg" in sdcard folder.
    String fileName = "";
    if (now){
        fileName = getDateTime()+"_00"+".png";
    }
    else {
        fileName = time.replace(".txt", ".png");
    }
    File f = new File(Environment.getExternalStorageDirectory()
            + File.separator + "appName/" + fileName);
    f.createNewFile(); // write the bytes in file
    FileOutputStream fo = new FileOutputStream(f);
    fo.write(bytes.toByteArray());
}

I think the trick is in File.separator!

respondido 09 mar '12, 21:03

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.