Use a variable as a file name?


I need to create an XML file whose name is the title and the date when it was created, to differentiate it from the other XML. The problem is that when I try to create the file an exception is thrown if the name of this one involves a variable:

File ruta_sd = Environment.getExternalStorageDirectory();
File f = new File(ruta_sd.getAbsolutePath(),"prueba.xml");
dos = new DataOutputStream(new FileOutputStream(f));

This creates it without problems, on the other hand if it were like this

File ruta_sd = Environment.getExternalStorageDirectory();
File f = new File(ruta_sd.getAbsolutePath(),momento+"prueba.xml");
dos = new DataOutputStream(new FileOutputStream(f));

Being a String where I save the date, it says that the file is not found and throws an exception, can any one illuminate me?

Variable moment:

    calendario= Calendar.getInstance();
    momento=dia+"/"+mes+"/"+año+" - "+hora+":"+minutos+":"+segundos;

This last in onCreate ()

asked by Angel Gonzalez Pena 05.12.2017 в 14:34

4 answers


If adding the moment variable as prefix of your file gives you the problem, it means that the problem is due to this variable.

Actually the variable moment would get a value as an example: "5/12/2017 - 10:10:10", if you add this value as a prefix to your file name, you would be trying to create a file:

/storage/emulated/0/5/12/2017 - 10:10:10prueba.xml

Actually the problem is the nomenclature that you add as a prefix to your file, it is not accepted by the file system, mainly because of the use of the symbol : , therefore I suggest changing the format , examples:

yyyy-MM-dd HH-mm-ss

If you use yyyy-MM-dd HH-mm-ss as a prefix, you would create it this way:

 String momento = año+"-"+mes+"-"+dia+" "+hora+"-"+minutos+"-"+segundos;

 File ruta_sd = Environment.getExternalStorageDirectory();
 File f = new File(ruta_sd.getAbsolutePath(), momento + "prueba.xml");
 DataOutputStream dos = new DataOutputStream(new FileOutputStream(f));

and you would have no problem to create your file with the date / time prefix.

File system utilities and Windows naming conventions prohibit certain characters from appearing in file names, check this table (the last two are "allowed", but with certain restrictions):

answered by 05.12.2017 / 16:56

Regardless of the language used, if you try to save a file with a colon ( : ) it will give you an exception because it is a special character that is not allowed.

There are several characters that are not allowed in the name of a file and they are the following:

\ / : * ? " < > |

If you substitute the two points with a low bar ( _ ) or another character that is not among the ones I have indicated above, it will work for you.


answered by 05.12.2017 в 15:58

I think the problem is that maybe the Date of "moment" has spaces or something like that, I do not know if in Android the class File , properly create the file in local, see if there is a class in Android similar to FileWriter that is just put the path and the name with the variable, creates it without problems. I hope I could have helped you.

public void crearArchivo(){
        Date momento = new Date();
        FileWriter f = null;
        SimpleDateFormat ft = new SimpleDateFormat ("yyyyMMddhhmmss");
        String momentostr = ft.format(momento);
        String filename = momentostr+"prueba.xml";
            f = new FileWriter(filename);
        catch (Exception e) { }
answered by 05.12.2017 в 15:21

I want to give my answer and argue that it complements several of the answers already described. Resolving the topic of the name of the file or folder (which can not contain special characters), because you do not try to validate the existence of the file and if it does not exist create it. Something like the following:

File folder = new File(Environment.getExternalStorageDirectory() + "/yourDirectoryName");//variable momento en un formato correcto
boolean success = true;
if (!folder.exists()) {
    success = folder.mkdir();
if (success) {
    // Codigo para crear archivo 
} else {
    // Algo sucedió mal... 

In this way you create the file, you need to take the path of this file: Environment.getExternalStorageDirectory() + "/" + momento; //esto es el path

This is an alternative and complements the answers of others. Also remember if it was helpful to help you up!

answered by 05.12.2017 в 19:38