Folder created instead of a file
I want to create a file in a defined directory, i tried this two codes but the first just creates folders and the other output an exception: no such file or directory: First code:
File file = new File(Environment.getExternalStorageDirectory()
+File.separator
+"carbu"
+File.separator
+"install");
file.mkdir();
Then i added this c开发者_JS百科ode hopefully to create the file:
File file2 = new File("/carbu/install/","voitu");
file2.createNewFile();
Can anyone please try to help me ? Thank you very much :).
Try this in your Activity:
FileOutputStream fos = openFileOutput(YOUR_FILE_NAME, Context.MODE_PRIVATE);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeInt(5);
oos.flush();
This will create file if it isn't exist. Of course you should close oos
and fos
.
Here is the most simple solution, working at 100% ;)
File dir = new File (sdCard.getAbsolutePath() + "/jetpack/install");
dir.mkdirs();
File file = new File(dir, "wipe");
have you tried:
File f=new File("myfile.txt");
if(!f.exists())
{
f.createNewFile();
}
In you example you are only giving the pathname to the file but you are not defining the type and the name of the new file.
http://download.oracle.com/javase/6/docs/api/java/io/File.html
Also try following:
String FILENAME = "/carbu/install/test.txt";
String string = "hello world!";
FileOutputStream fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);
fos.write(string.getBytes());
fos.close()
got the above example from: http://developer.android.com/guide/topics/data/data-storage.html
try {
File root = Environment.getExternalStorageDirectory();
if (root.canWrite()){
File gpxfile = new File(root, "gpxfile.gpx");
FileWriter gpxwriter = new FileWriter(gpxfile);
BufferedWriter out = new BufferedWriter(gpxwriter);
out.write("Hello world");
out.close();
}
} catch (IOException e) {
Log.e(TAG, "Could not write file " + e.getMessage());
}
While you were careful in constructing the path correctly in the first segment, you just hard-coded the wrong path in the second part. Ensure you use the correct path, possibly as follows:
String path = Environment.getExternalStorageDirectory().getAbsolutePath()
+File.separator
+"carbu"
+File.separator
+"install";
File file = new File(path);
file.mkdir();
File file2 = new File(path + File.separator + "voitu");
file2.createNewFile();
精彩评论