Files deleting issue - java

I have this code, which must remove files from the directory and the directory itself:
private static void removeTempFiles(File dir){
if(!dir.exists())
return;
if(dir.isDirectory()){
for(File f : dir.listFiles())
removeTempFiles(f);
dir.delete();
}
else {
dir.delete();
}
}
but executing this code don't remove all the files. From time to time it removes all files with the folder or removes only a few files
UPD:
here is my creating file code:
File tempFolder = new File(tempPath);
tempFolder.mkdir();
tempFolder.mkdirs();
FileOutputStream fileOut = new FileOutputStream(tempPath+"/"+fileName);
OutputStreamWriter osw = new OutputStreamWriter(fileOut, "windows-1251");
try{
osw.write(file64);
} catch (IOException e){
e.printStackTrace();
}finally {
osw.close();
fileOut.close();
}

On Windows, it's normal that file deletion does not always succeed, because files can be locked by various services running on the system (antivirus, search indexing etc.). You need to add a retry loop around every file deletion call.

Related

BufferedWriter works on Windows but not Mac

So I am using this method to write to a file, it works totally fine on windows but when run on mac it creates the files but they are empty.
public static void writeLinesToTextFile(String path, String[] lines) {
File file = new File(r + path);
if (!file.exists()) {
try {
file.getParentFile().mkdirs();
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
BufferedWriter bw;
try {
bw = new BufferedWriter(new FileWriter(file.getPath()));
file.delete();
file.createNewFile();
for (int i = 0; i < lines.length; i++) {
//System.out.println(lines[i]);
bw.write(lines[i]);
bw.write(System.getProperty("line.separator"));
}
bw.flush();
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
I know the data is right because it prints correctly.
Thanks for any help, this has really been tripping me out.
Don't delete the file after creating a BufferedWriter. In Linux, every file has a unique file handle, so deleting and recreating a file with the same path creates 2 different file handles. I don't know what Windows does as I don't consider it a real OS, but from your post, it appears that it uses the same file handle.

Temporary File not deleted on close

I'm using Java in a really big application and some time i have to use temp file. Those file i want to be deleted at the application close, this is a simple snapshot i'm using:
File tempFile = File.createTempFile("sign_", "tmp.pdf");
tempFile.deleteOnExit();
I'm not reporting all the code since is really big and i have many class working each other. I would know which could be the reason that avoid the delete on closure of certain file (some file are deleted other not, but they came always from the same piece of code the one that are not deleted).
Edit: i have already read this example but i think i need some "theoric" motivation and not code example to find the reason.
The method "deleteOnExit()" only works if the VM terminates normally. If the VM crash or forced termination the file might remain undeleted.
I don't know how it is implemented, but you could try to put the tempFile.deleteOnExit() inside the finally.
File tempFile = null;
try{
tempFile = File.createTempFile("sign_", "tmp.pdf");
}catch(IOException e){
e.printStackTrace();
} finally {
if (tempFile != null) {
tempFile.deleteOnExit();
tempFile = null;
//Added a call to suggest the Garbage Collector
//To collect the reference and remove
System.gc();
}
}
Or maybe, close all the references to the file and then call "File.delete()" to delete immediate.
If anyone is working, problably some reference to the file exists. In this way, you can try to force the file to be deleted using the org.apache.commons.io.FileUtils.
Example org.apache.commons.io.FileUtils:
File tempFile = null;
try{
tempFile = File.createTempFile("sign_", "tmp.pdf");
}catch(IOException e){
e.printStackTrace();
} finally {
if (tempFile != null) {
FileUtils.forceDelete(tempFile);
System.out.println("File deleted");
}
}
Example org.apache.commons.io.FileDeleteStrategy:
File tempFile = null;
try{
tempFile = File.createTempFile("sign_", "tmp.pdf");
}catch(IOException e){
e.printStackTrace();
} finally {
if (tempFile != null) {
FileDeleteStrategy.FORCE.delete(tempFile);
System.out.println("File deleted");
}
}

Writing to an External File on Android --- File Doesn't Register, But Java Can Read

I'm trying to write to an external txt (or csv) file for Android. I can run an app, close it, and run it again, and readData() will read back to my log what I've stored. However, the dirFile (file directory) appears nowhere within my Android files (even if I connect it to a computer and search).
Something interesting, though: if I clear my log (similar to a list of print statements shown within Eclipse) and disconnect my phone from my computer, then reconnect it, the log reappears with everything I've ever written to my file (even if I later overwrote it)...yet the app isn't even running!
Here is my code. Please help me understand why I cannot find my file!
(Note: I've tried appending a "myFile.txt" extension to the directory, but it just causes an EISDIR exception.)
public void writeData(String dirName){
try
{
File root = new File(getExternalFilesDir(null), dirName);
// Writes to file
//
// The "true" argument allows the file to be appended. Without this argument (just root),
// the file will be overwritten (even though we later call append) rather than appended to.
FileWriter writer = new FileWriter(root, true);
writer.append("Append This Text\n");
writer.flush();
writer.close();
// Checks if we actually wrote to file by reading it back in (appears in Log)
//readData(dirName);
}
catch(Exception e)
{
Log.v("2222", "2222 ERROR: " + e.getMessage());
}
}
If you're interested, here's the function I wrote to read in the data:
public void readData(String dirName){
try
{
File root = new File(getExternalFilesDir(null), dirName);
// Checks to see if we are actually writing to file by reading in the file
BufferedReader reader = new BufferedReader(new FileReader(root));
try {
String s = reader.readLine();
while (s != null) {
Log.v("2222", "2222 READ: " + s);
s = reader.readLine();
}
}
catch(Exception e) {
Log.v("2222", "2222 ERROR: " + e.getMessage());
}
finally {
reader.close();
}
}
catch(Exception e) {
Log.v("2222", "2222 ERROR: " + e.getMessage());
}
}
Thanks!
even if I connect it to a computer and search
if I clear my log (similar to a list of print statements shown within Eclipse) and disconnect my phone from my computer, then reconnect it, the log reappears with everything I've ever written to my file (even if I later overwrote it).
What you are seeing on your computer is what is indexed by MediaStore, and possibly a subset of those, depending upon whether your computer caches information it gets from the device in terms of "directory" contents.
To help ensure that MediaStore indexes your file promptly:
Use a FileOutputStream (optionally wrapped in an OutputStreamWriter), not a FileWriter
Call flush(), getFD().sync(), and close() on the FileOutputStream, instead of calling flush() and close() on the FileWriter (sync() will ensure the bytes are written to disk before continuing)
Use MediaScannerConnection and scanFile() to tell MediaStore to index your file
You can then use whatever sort of "reload" or "refresh" or whatever option is in your desktop OS's file manager, and your file should show up.
This blog post has more on all of this.
public void create(){
folder = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MOVIES),"video");
boolean success = true;
if (!folder.exists()) {
success=folder.mkdirs();
}
if (success) {
readfile();
} else {
System.out.println("failed");
}
}
The above code will be used to crete the directory in th emobile at desired path
private void readfile() {
// TODO Auto-generated method stub
AssetManager assetManager = getResources().getAssets();
String[] files = null;
try {
files = assetManager.list("clipart");
} catch (Exception e) {
Log.e("read clipart ERROR", e.toString());
e.printStackTrace();
}
for(String filename : files) {
System.out.println("File name => "+filename);
InputStream in = null;
OutputStream out = null;
try {
in = assetManager.open("clipart/" + filename);
out = new FileOutputStream(folder + "/" + filename);
copyFile(in, out);
in.close();
in = null;
out.flush();
out.close();
out = null;
} catch(Exception e) {
Log.e("copy clipart ERROR", e.toString());
e.printStackTrace();
}
}}private void copyFile(InputStream in, OutputStream out) throws IOException {
byte[] buffer = new byte[1024];
int read;
while((read = in.read(buffer)) != -1){
out.write(buffer, 0, read);
}}
this is my code used to write file in internal memory from the assets folder in project. This code can read all type(extension) of file from asset folder to mobile.
Don't forget to add permission in manifest file
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
and call the above function by
readfile();//this call the function to read and write the file
I hope this may help you.
Thank you.

Unable to located generated file

I am generating a file using the following syntax
File file = new File("input.txt");
The problem is that it is saying that it is writing to the file but I am not able to locate where the file is created, I searched my entire workspace. The expectation was that it would be created in the same folder as my code which is executing.
Any ideas?
Rest of the code :
File file = new File("input.txt");
// if file doesnt exists, then create it
if (!file.exists()) {
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
You could do a sop on the absolute path and you would get the path:
File file = new File("input.txt");
System.out.println("" + file.getAbsolutePath());
if (!file.exists()) {
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
When you create file through relative paths, Java uses System.getProperty("user.dir"). So, in your case the full path to file will be System.out.println(System.getProperty("user.dir") + "/input.txt");.

Problem in Zipping a File

When I run my code and use the files that are in the resource folder of my project itself, I face no problems. It zips the file successfully and I can extract it using WINZIP. The problem comes when I try to zip a file that is not in the project folder.
When I do the same, I am passing the Absolute Path of both the src and the dest files. My program doesn't give any exceptions, but when I try to open that zip file, I get an error saying, File is Invalid.
Can anyone tell me why this may be happening.
public static void compress(String srcPath, String destPath) {
srcFile = new File(srcPath);
destFile = new File(destPath);
try {
fileInputStream = new FileInputStream(srcFile);
fileOutputStream = new FileOutputStream(destFile);
zipEntry = new ZipEntry(srcPath);
zipOutputStream = new ZipOutputStream(fileOutputStream);
zipOutputStream.putNextEntry(zipEntry);
byte[] data = new byte[12];
while ((fileInputStream.read(data)) != -1) {
zipOutputStream.write(data);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try{
fileInputStream.close();
zipOutputStream.close();}catch (Exception e) {
e.printStackTrace();
}
}
}
You should not store paths with drive letters in your zip file because when you try to extract your zip, it will try to create a directory with the name of the drive and fail.
You will need to change your code so that it removes the drive letter from the path before creating the ZipEntry.

Categories

Resources