I am working on an android app and I want to rename a file. The problem is that it is not renaming:
File f = adapter.getItem(i);
File file = new File(f.getAbsolutePath(), "helloworld");
if (f.renameTo(file)) {
Toast.makeText(getActivity(), "done", Toast.LENGTH_LONG).show();
}
Solution BIg Thanks to #S.D.(see comments)
File f = adapter.getItem(i);
File file = new File(f.getParent(), "helloworld");
if (f.renameTo(file)) {
Toast.makeText(getActivity(), "done", Toast.LENGTH_LONG).show();
}
I think the issue is that:
File f = adapter.getItem(i);
Gives use some File f, say where f cooresponds to say: user2351234/Desktop. Then, you do:
File file = new File(f.getAbsolutePath(), "helloworld");
Which says to make a File file, where file cooresponds to: user2351234/Desktop/helloworld. Next, you call:
f.renameTo(file)
which attempts to rename f, user2351234/Desktop to user2351234/Desktop/helloworld, which doesn't make sense since in order for user2351234/Desktop/helloworld to exist, user2351234/Desktop would have to exist, but by virtue of the operation it would no longer exist.
My hypothesis may not be the reason why, but from Why doesn't File.renameTo(…) create sub-directories of destination?, apparently renameTo will return false if the sub-directory does not exist.
If you want to just change the name of the file, do this:
File f = adapter.getItem(i);
String file = f.getAbsolutePath() + "helloworld";
f = new File(file);
EDIT:
My proposed solution should work, but if my hypothesis about why your way does not work is incorrect, you may want to see this answer from Reliable File.renameTo() alternative on Windows?
Question 1: Do you see an exception or does it return false?
Question 2: Did you give permission for the app to write to the SD card? (I'm assuming that's where this file lies).
The permission to add is"
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
This posting: How to rename a file on sdcard with Android application? seems to answer a similar question.
use this code.
File sdcard = Environment.getExternalStorageDirectory()+ "/nameoffile.ext" ;
File from = new File(sdcard,"originalname.ext");
File to = new File(sdcard,"newname.ext");
from.renameTo(to);
Related
Here is my code:
String dir = getFilesDir().getAbsolutePath();
File myFile = new File(dir+"/file.apk");
if (myFile.exists())
{
textView.setText("File exists.");
}
else
{
textView.setText("File does not exist.");
}
myFile.exists() is false. I do not know why. The file exists and it is located in the directory.
When I solve the problem, I'll try this:
Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
intent.setData(Uri.fromFile(myFile));
intent.putExtra(Intent.EXTRA_NOT_UNKNOWN_SOURCE, true);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
Can somebody help? Why it does not see the file?
UPDATE:
It's really strange. If I use code:
if (myFile.exists())
{
textView.setText("it exists");
}
else
{
textView.setText(myFile.getAbsolutePath());
}
, it goes to 'else' and shows the path to the file which 'does not exist'.
Thanks to greenapps:
"Please click in Astro app left to the word Primary on the up arrow to see the real path. /Primary/ does not exist on an Android device. It's an Astro invention. And Astro shows external memory with Primary. And take a better file explorer like ES File Explorer to inform you about real paths"
I used direct path I found using Astro (modified string dir to '/sdcard/data/data/...").
Try using this code:
String dir = getFilesDir().getAbsolutePath();
boolean fileExists = (new File(dir + "/file.apk")).isFile();
if (fileExists)
{
// your file exists
}
else
{
// your file does not exist
}
If you construct the file with the 2-arg constructor, you can avoid adding a system-dependent path separator character. Like this:
File myFile = new File(dir, "file.apk");
trying to rename internal file within a zip file without having to extract and then re-zip programatically.
example. test.zip contains test.txt, i want to change it so that test.zip will contain newtest.txt(test.txt renamed to newtest.txt, contents remain the same)
came across this link that works but unfortunately it expects test.txt to exist on the system. In the example the srcfile should exist on the server.
Blockquote Rename file in zip with zip4j
Then icame across zipnote on Linux that does the trick but unfortunately the version i have doesnt work for files >4GB.
Any suggestions on how to accomplish this? prefereably in java.
This should be possible using Java 7 Zip FileSystem provider, something like:
// syntax defined in java.net.JarURLConnection
URI uri = URI.create("jar:file:/directoryPath/file.zip");
try (FileSystem zipfs = FileSystems.newFileSystem(uri, Collections.<String, Object>emptyMap())) {
Path sourceURI = zipfs.getPath("/pathToDirectoryInsideZip/file.txt");
Path destinationURI = zipfs.getPath("/pathToDirectoryInsideZip/renamed.txt");
Files.move(sourceURI, destinationURI);
}
Using zip4j, I am modifying and re-writing the file headers inside of the central directory section to avoid rewriting the entire zip file:
ArrayList<FileHeader> FHs = (ArrayList<FileHeader>) zipFile.getFileHeaders();
FHs.get(0).setFileName("namename.mp4");
FHs.get(0).setFileNameLength("namename.mp4".getBytes("UTF-8").length);
zipFile.updateHeaders ();
//where updateHeaders is :
public void updateHeaders() throws ZipException, IOException {
checkZipModel();
if (this.zipModel == null) {
throw new ZipException("internal error: zip model is null");
}
if (Zip4jUtil.checkFileExists(file)) {
if (zipModel.isSplitArchive()) {
throw new ZipException("Zip file already exists. Zip file format does not allow updating split/spanned files");
}
}
long offset = zipModel.getEndCentralDirRecord().getOffsetOfStartOfCentralDir();
HeaderWriter headerWriter = new HeaderWriter();
SplitOutputStream splitOutputStream = new SplitOutputStream(new File(zipModel.getZipFile()), -1);
splitOutputStream.seek(offset);
headerWriter.finalizeZipFile(zipModel, splitOutputStream);
splitOutputStream.close();
}
The name field in the local file header section remains unchanged, so there will be a mismatch exception in this library.
It's tricky but maybe problematic, I don't know..
I am trying to check if a file exits on android sd card...so i do:
File f=new File(sdpath + "/" + DATABASE_NAME); //
if(!f.exits()) {
...create new file..
}
else {
...do something...
}
Every time this actually creates the directory or file on the sd card.
I know it doesnt exist, and when the new File is executed it is created and it shouldnt ?
I read all across google that new File doesnt create an actual file on the file system , but in my case it does...
Any alternatives to checking if a File/directory exits without using new File..
Edit 1: Well I'd just like to add (after 4 years :)) that this problem occurred only on two devices at the time i was writing the post and never again, one of them was HTC Desire C with android 4.0 and the other was some Huawei with android 2.x, cant remember anymore.
For some strange reason it turned out that new File created a directory every time...
instead of checking if (!f.exists()), I changed it to checking if (!f.isFile())
In that case i create a new file and it works good, the next time i run it the file is already on the sd card...
The way that worked was nearly like yours:
File f = new File(Environment.getExternalStorageDirectory(), "a directory");
if(!f.exists){
// do something
}
and to check whether a file exists or not is almost the same way:
File f = new File(Environment.getExternalStorageDirectory() + "/a directory/" + "a file");
if(!f.exists){
// do something
}
I hope it can help you out, because it didn't create a file or directory in my app. It just checked the path.
this may helps you, try like
if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
//handle case of no SDCARD present
} else {
File file = new File(Environment.getExternalStorageDirectory()
+File.separator
+"myDirectory" //folder name
+File.separator
+"myFile.example"); //file name
if(file.exists()){
Toast.makeText(MainActivity.this, "Not Create ", 12).show();
}else{
file.mkdirs();
Toast.makeText(MainActivity.this, "Create ", 12).show();
}
}
Try this
File[] files = filedir.listFiles();
for (File file2 : files) {
if (file2.isDirectory()) {
Toast.makeText(this, "directory", Toast.LENGTH_LONG).show();
} else {
if (file2.getName().equals(DATABASE_NAME)) {
Toast.makeText(this, "File found",Toast.LENGTH_LONG).show();
}
else{Toast.makeText(this, "File not found",Toast.LENGTH_LONG).show();
}
}
}
This question already has answers here:
How to delete a file from SD card
(14 answers)
Closed 9 years ago.
I use this code:
String path = "mnt/sdcard/ten-file.mp3";
File file = new File(path);
boolean result = file.delete();
But it doesn't delete the file. Any advice?
String fileName = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "ten-file.mp3";
File soundFile = new File(fileName);
if (soundFile.exists())
{
boolean result = file.delete();
}
Manifest permission
uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"
You want to make sure that the file exists prior to actually deleting the file:
File file = getBaseContext().getFileStreamPath("/sdcard/appname/data.xml");
if(file.exists()) {
boolean result = file.delete()
}
The issue I think with your original code is that you didn't actually test to make sure the file existed. You just created a file variable then told it delete it. I referred to the following question from an individual who had a similar problem to you:
Android how to check if file exist and else create one?
I'm sorry for a rather green question, but I could not find solution yet.
I am trying to restore a database from a back up on SD Card. The following code (a slight modified version of one provided here in SO)
try {
File sd = Environment.getExternalStorageDirectory();
File data = Environment.getDataDirectory();
if (sd.canWrite()) {
String currentDBPath =
"\\data\\com.dg\\databases\\" + com.dg.Constants.db_Table;
String backupDBPath = "com.dg";
File currentDB = new File(data, currentDBPath);
File backupDB = new File(sd, backupDBPath);
if (currentDB.exists()) {
FileChannel dst = new FileInputStream(currentDB).getChannel();
FileChannel src = new FileOutputStream(backupDB).getChannel();
dst.transferFrom(src, 0, src.size());
src.close();
dst.close();
}
line4.setText("Successful Import");
}
} catch (Exception e) {
line4.setText(e.toString());
}
Throws NonWriteableChannelException even though the database file is not open.
Your data is GENERALLY in
/data/data/com.dg/databases
You need to get rid of the double \ in the path.
Also, you're using Environment.getDataDirectory() as the parent directory, then "\data\com.dg\databases\"(etc) as the file name. That's totally wrong.
The easy way to go might be 'getDatabasePath' in Context (or Activity). Give it the name of your DB and it should give you a File reference to it. However, I don't know what it would do if that File didn't exist yet.
http://developer.android.com/reference/android/content/Context.html#getDatabasePath(java.lang.String)
You may also try simple 'getDir("databases", MODE_PRIVATE)'. That would hopefully return the database dir.
Final try for the database dir, really dirty:
File dbDir = new File(getFilesDir().getParentFile(), "databases");
Does your user / app have permissions to //database? (If not, then THIS IS THE ANSWER.)
Perhaps this might tell you why permission is denied:
IOException: Permission Denied
Bill Mote (from the above link) also pointed out the following permission setting:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />