Java: File output help - java

Fixed: Instead of calling isFile() I used exists() and it seems to be working fine. If possible could someone explain why this change worked?
I'm attempting to write out to an excel file but am having a problem when trying to create that file if the name already exists.
Basically I am taking a file that is uploaded to a server, reading it, and then outputting a report file in a new location with the same filename. I tried to do this by simply checking if the file already existed and then adding a number onto the filename. My code works if the file doesn't exist or if it exists without a number (e.g. filename.xls). If a file exists with the name "filename1.xls" the server just seems to hang when trying to write the file. What can do to fix this?
Here is my code:
String destination = "c:/apache-tomcat-7.0.8/webapps/reports/" + fileName.substring( fileName.lastIndexOf("\\")+1, fileName.lastIndexOf(".")) + ".xls";
int filenum = 1;
while (new File(destination).isFile()) {
destination = "c:/apache-tomcat-7.0.8/webapps/reports/" + fileName.substring( fileName.lastIndexOf("\\")+1, fileName.lastIndexOf(".")) + filenum + ".xls";
filenum++;
}
WritableWorkbook workbook = Workbook.createWorkbook(new File(destination));

That will happen if some process is still keeping the file open. E.g. you've created a FileInputStream on the file to read it, but are never calling close() on it after reading.
Unrelated to the problem, the expanded WAR folder is not the best place to use as a permanent storage. All those files in the expanded WAR folder will get lost whenever you redeploy the WAR. Also hardcoding a servletcontainer-specific path in the code makes it totally unportable.
If your actual intent is to return the Excel file on a per-request basis to the client using a servlet, then you should be using
WritableWorkbook workBook = Workbook.createWorkbook(response.getOutputStream());
// ...
This way it writes to the response immediately without the need for an intermediate file.

Use the File.createTempFile(prefix, suffix, directory) API:
String localName = new File(fileName).getName();
String nameNoExt = localName.substring(0, fileName.lastIndexOf("."));
String extension = localName.substring(fileName.lastIndexOf(".")); // need to include the .
File directory = new File("c:/apache-tomcat-7.0.8/webapps/reports/");
File destFile = File.createTempFile(nameNoExt, extension, directory)

Related

File Not Found exception: (file exists) - after manually deleting it

I've stumbled upon an issue that has been puzzling me. I'm writing an app that creates mp3 files on the external storage. The thing is, if I manually go to the created directory on the phone and delete the file, whenever I try to the create the same file it throws this error:
java.io.FileNotFoundException: /storage/emulated/0/Ringtones/sound1.mp3: open failed: EEXIST (File exists)
Selecting other sounds to be created works just fine, but after I manually delete them they can't be created again due to that issue.
I've already tried deleting the file right after indicating the path and before FileOutputStream but didn't work.
Any tips?
Cheers.
You need to acknowledge the media database before trying to create another copy of the same file. So you need to call this before copying:
sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(folder path in which your file was)));
Edit: The above answer is deprecated! Please use the following method:
File file = new File(outputPath + fileName);
String filePath = file.toString();
String mimeType = "video/mp4";
MediaScannerConnection.scanFile(this, new String[]{filePath}, new String[]{mimeType}, null);
Example of outputPath and fileName:
String outputPath = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM), "My App Name") + "/";
String fileName = "break dance" + ".mp4";
So the File file should be the path of the media you want to update either because it's just deleted or it's newly added, to be visible in Gallery.
Found the answer, following user blackapps' tip. I also changed the directory, as I was using a deprecated reference. Now it is working as intended for sdk 30.

Creating tmp file in java using java nio classes , but to file name some random is getting appended , how to remove that?

I am using java nio to create the tmp file like below
Path tempFile = Files.createTempFile("student_records", ".csv");
Files.write(tempFile, fileContents);
File file = tempFile.toFile();
return new FileSystemResource(file);
but when file is created in temp directory , the file is not student_records.csv but student_records122334343443434.csv , i mean some random number is appending to the file , i do not want that random number , how to do that , and i want confirmation on if application exited, this tmp files deleted automatically or not ? can someone please help on this
This is intended behaviour of Files.createTempFile().
If you want a file that you can explicitly set the name of that does not exist after the application is closed, you can use:
File file = new File("student_records.csv");
file.deleteOnExit();
This will (as the name suggests) delete the file when the program exits.

FileOutputStream not written to disk on server? Where does the file go?

I've been trying to generate report files with Dynamic Reports, however it just doesn't seem to create files on Server. When I use the same method running locally it generates the file, however when I run it on server, there are not files created. I'm running Tomcat 7 in Eclipse. The file is supposed to be created using FileOutputStream.
Well here's the method that works locally, but not on Tomcat:
StyleBuilder plainStyle = stl.style().setFontName("FreeUniversal");
StyleBuilder boldStyle = stl.style(plainStyle).bold();
StyleBuilder italicStyle = stl.style(plainStyle).italic();
StyleBuilder boldItalicStyle = stl.style(plainStyle).boldItalic();
try {
report().title(
Templates.createTitleComponent("Fonts"),
cmp.text("FreeUniversal font - plain").setStyle(plainStyle),
cmp.text("FreeUniversal font - bold").setStyle(boldStyle),
cmp.text("FreeUniversal font - italic").setStyle(italicStyle),
cmp.text("FreeUniversal font - bolditalic").setStyle(boldItalicStyle))
.toDocx(createFile("docx"))
// .show()
;
} catch (DRException e) {
e.printStackTrace();
}
Oh and the CreateFile(...) method:
private FileOutputStream createFile(String extension) throws FileNotFoundException {
FileOutputStream file;
String filePath = reportsPath + "generated_report." + extension;
filePath = "generated_report." + extension;
System.out.println("FILENAME IS: " + filePath);
file = new FileOutputStream(new File(filePath));
return file;
}
I know the reportsPath here is not active.
So there are no exceptions. By the way, it might be possible that other files don't get created on this server too, because I'm also uploading a file via servlet and it get used, however it doesn't appear anywhere in the path and it doesn't seem to be saved, but I don't need to keep the uploaded files anyway, so it wasn't much of a concern, but now this? I need to be able to find those reports, so the files must get created.
And I'm sure it's not that I can't find the files, I've run the search everywhere, actually in all of my computer on which the server is running, there were no files created with that name...
So, any ideas? It must be a Tomcat configuration issue or something?
Any ideas? Thanks
The output was written to the file you supplied in the constructor. If that was a relative filename, it is relative to the current working directory when you executed the code.
Or else an IOException was thrown and the code didn't execute at all.

JAVA - Get access to a file in different subfolder

I am programming a file transfer, and i am having troubles with it.
In my current location i have created a folder called "Server Folder", where i will have files that the Client can transfer (I will be transfered with the same name, to the workspace directory), But every time i try to access it, it fails.
FILE_SERVER_PATH = "./ServerFolder/";
File fileToRead = new File(FILE_SERVER_PATH + fileName);
fileToRead = fileToRead.getParentFile();
if(fileToRead.exists()){
FileInputStream readingBuffer = new FileInputStream(fileToRead);
fileName is received throw datagram, and the name is correct. It always fails in the condition --> fileToRead.exists()
Can anyone please give me a tip?
Thx! :-)
try to use the folder path as absolute.
will help and work...current directory works only if you know in which directory you are in at the time of execution.

What is my directory when writing files in Android?

FileOutputStream fos = openFileOutput(FILENAME, Context.MODE_WORLD_READABLE);
fos.write(string.getBytes());
fos.close();
When trying to delete one of those files, this is what I use, but it's returning false.
String tag = v.getTag().toString();
File file = new File(System.getProperty("user.dir")+"/"+tag);
String s = new Boolean (file.exists()).toString();
Toast.makeText(getApplicationContext(), s, 1500).show();
file.delete();
How can I overcome this problem?
Use getFileStreamPath(FILENAME) to find your file. From the docs:
Returns the absolute path on the filesystem where a file created with openFileOutput(String, int) is stored.
Your current working directory.
To help diagnose the problem, use file.getAbsolutePath() to see the full path.
It could also be a permissions problem, if you're trying to delete from another application. If so, you may need to change to MODE_WORLD_WRITEABLE (insecure), or restructure your code so the create and delete are called by the same app.
EDIT: That was mostly incorrect. I didn't realize that openFileOutput didn't use the current working directory.
Use same contents as 'FILENAME' variable in your first snippet in the second snippet while trying to delete.
String RootDir = Environment.getExternalStorageDirectory()
+ File.separator + "Video";
File RootFile = new File(RootDir);
RootFile.mkdir();
FileOutputStream f = new FileOutputStream(new File(RootFile, "Sample.mp4"));
i used this code to save the video files to non-default location. Hope this will be useful to you.By default it is storing in sd card
For each application the Android system creates a "data/data/package of the application" directory.
Files are saved in the "files" folder under this directory
to change the default directory the above code will be used
the default working directory can be displayed using fileobject.getAbsolutePath()

Categories