I am attempting to write a JApplet that uses information in a text file to load and save data from. I have successfully got the applet to load the information, but the saving appears to be having issues. I have included the code to save below. the file name I am using is the same as I use to write to. The file must be included in the JAR when I run because the applet initializes properly. Is there any reason why the writing sin't working properly? i have resorted to calling this method from both the stop() and destroy() methods.
As a note, the load and saving both work perfectly when run from eclipse, but when in a JAR only the loading works, but nothing saves so I can't change the load data.
Ideally, I want this saveLocations() method to be called whenever the page is closed or refreshed.
NOTE: mOUtputStream is indeed a PrintWriter (it used to be an OutputStream, I guess I should change the name)
Thanks so much in advance for the help.
private void saveLocations() throws IOException {
//JOptionPane.showMessageDialog(null, "Alert", "Saving", JOptionPane.INFORMATION_MESSAGE);
// System.out.println("saving!");
try {
mOutputStream = new PrintWriter(new File(getClass().getResource("/listings/saveData.txt").toURI()));
}
catch (URISyntaxException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//System.out.println(locations.size());
for (Location l : locations) {
System.out.println("r: " + l.getRawListing());
mOutputStream.print(l.getRawListing()+ "\n");
}
if (mOutputStream != null)
mOutputStream.close();
}
You can't write to a file inside a JAR file -- period. Don't even try. If you need to write to a file, then that file has to be outside the JAR. For an applet, that would require it to be signed, and to ask the user for specific permission to do so.
In the applet case, I'm not sure what copy of the JAR file you're hoping will be written to: the copy in the browser cache, or the copy on the server? Either way, it's not going to happen.
Related
I got a problem when i want to update my (lets say orderNumber) and i try to renaming the file of image. lets say the original file ini MainImage15 i want to rename to MainImage16 with Files.Copy or Files.Move and after that i try to delete after succesful copying. and i got the error like this
java.nio.file.FileSystemException: C:\Users\User\apache\webapps\Promotion\030000\MainImage15.jpg: The process cannot access the file because it is being used by another process.
public void renameFileToFileSystem(final String fileName, final String oldFileLocation, final String newFileLocation) {
Path source = Paths.get(oldFileLocation);
Path destination = Paths.get(newFileLocation);
try {
Files.copy(source, destination, StandardCopyOption.REPLACE_EXISTING);
Files.delete(source);
} catch (final IOException ioException) {
throw new ContentManagementException(fileName, ioException.getMessage());
}
}
i dont knwo what to do. should i use buffer close? but i just renaming the file . thankyou.
I don't think Files.copy keeps the file handle open.
To make sure its true - remove the line Files.copy and rerun - the chances are that you still won't be able to delete the file.
So you must find who keeps the handle busy. There are basically two possibilities:
Its somewhere else in your code
Its some kind of external process (antivirus, another application that you've used to render the image and so forth). You can use Process Explorer that will help to find the process that keeps the handle.
I basically want to make a watch service (or something like it) that checks if a file has been closed and instantly remove that file if it did close(finished executing).
How I can achieve this? please give me a cmd commands or some code(i prefer Java).
Ok, this should not be hard to do, if you google a bit you find a Java-File Method called file.canWrite() which basically returns if a file is locked by an other program or so.
So codewise what you could do is something like this.
boolean isDeleted = false;
File f = new File (// Put your file here);
while (!isDeleted) {
if (f.canWrite()) {
f.delete();
isDeleted = true;
} else {
try {
Thread.sleep(10); // Throws Exception you need to catch somewhere...
} catch (Exception e) {}
}
}
This code you need to include into some Java-Program. I added a simple Thread.sleep(10) that your PC does not have to check aaaaaalllllllll the time.
See Check if a file is locked in Java
Other possibility would be trying to rename the file with file.renameTo("some_path.txt"); as this method also returns a boolean whether it was successfull! Just note that you then need to update the file again before removing it.
Last possibility I see is pretty similar to the second one. You try to delete the file by calling file.delete(); If the file still exists you know it was not successful and loop because of that.
I assume you mean when the file is not open in another program, and you cannot make changes to that other program? (If you are talking about your own program opening the file, this is much easier.)
On Windows, it is not very easy to tell which program has a file open. Take a look at https://superuser.com/questions/117902/find-out-which-process-is-locking-a-file-or-folder-in-windows for some options. I like the handle tool for this, but it has to run as Administrator, which may be a problem. You can try renaming or writing to the file, as suggested at Check if a file is locked in Java
Once you have a script that determines whether the file is open to your satisfaction, it should be fairly straightforward to write a script which loops while testing if the file is open and then deletes file.
I am new to android and currently trying to save a few files in a little "play-around" application I am making to learn, however the files only seem to persist until the application is shut down. When I run:
file.exists()
file.isFile()
or any similar methods they always return false when the application is restarted.
This is the method I found online to save files:
public void writeToFile(String data, String filePath, Context context){
File file = new File(context.getFilesDir(), filePath);
if(!file.exists()){
try{
file.createNewFile();
}catch(IOException e) {
e.printStackTrace();
Log.e("Exception", "File couldn't be created");
}
}
try {
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(context.openFileOutput(filePath, Context.MODE_PRIVATE));
outputStreamWriter.write(data);
outputStreamWriter.close();
}
catch (IOException e) {
Log.e("Exception", "File write failed: " + e.toString());
}
}
I have been googling a lot trying to find a solution but none of them worked. It seems to work when the application is running since I can write and read the files, however at a restart of the application, it cannot find the files. (file.exists() returns false)
I just spend an hour tracking down this same bug and it turned out it was because the "Clear User Data" flag was set under "Deployment" in the project properties. I'm using NVIDIA CodeWorks for Android with Visual Studio 2017.
I assume that you are attempting to write to internal storage here? If not and you wish to access external storage, I would suggest having a look through the guidance on Android.com below.
https://developer.android.com/guide/topics/data/data-storage.html#filesInternal
If this is internal storage that you are trying to write to, then you need to make sure that you are passing the correct context to the method. For example, if you were running from your MainActivity class and the method was contained within that class, your call would be something along the lines of:
writeToFile("Some data", "aFile.txt", MainActivity.this)
I need to write a custom batch File renamer. I've got the bulk of it done except I can't figure out how to check if a file is already open. I'm just using the java.io.File package and there is a canWrite() method but that doesn't seem to test if the file is in use by another program. Any ideas on how I can make this work?
Using the Apache Commons IO library...
boolean isFileUnlocked = false;
try {
org.apache.commons.io.FileUtils.touch(yourFile);
isFileUnlocked = true;
} catch (IOException e) {
isFileUnlocked = false;
}
if(isFileUnlocked){
// Do stuff you need to do with a file that is NOT locked.
} else {
// Do stuff you need to do with a file that IS locked
}
(The Q&A is about how to deal with Windows "open file" locks ... not how implement this kind of locking portably.)
This whole issue is fraught with portability issues and race conditions:
You could try to use FileLock, but it is not necessarily supported for your OS and/or filesystem.
It appears that on Windows you may be unable to use FileLock if another application has opened the file in a particular way.
Even if you did manage to use FileLock or something else, you've still got the problem that something may come in and open the file between you testing the file and doing the rename.
A simpler though non-portable solution is to just try the rename (or whatever it is you are trying to do) and diagnose the return value and / or any Java exceptions that arise due to opened files.
Notes:
If you use the Files API instead of the File API you will get more information in the event of a failure.
On systems (e.g. Linux) where you are allowed to rename a locked or open file, you won't get any failure result or exceptions. The operation will just succeed. However, on such systems you generally don't need to worry if a file is already open, since the OS doesn't lock files on open.
// TO CHECK WHETHER A FILE IS OPENED
// OR NOT (not for .txt files)
// the file we want to check
String fileName = "C:\\Text.xlsx";
File file = new File(fileName);
// try to rename the file with the same name
File sameFileName = new File(fileName);
if(file.renameTo(sameFileName)){
// if the file is renamed
System.out.println("file is closed");
}else{
// if the file didnt accept the renaming operation
System.out.println("file is opened");
}
On Windows I found the answer https://stackoverflow.com/a/13706972/3014879 using
fileIsLocked = !file.renameTo(file)
most useful, as it avoids false positives when processing write protected (or readonly) files.
org.apache.commons.io.FileUtils.touch(yourFile) doesn't check if your file is open or not. Instead, it changes the timestamp of the file to the current time.
I used IOException and it works just fine:
try
{
String filePath = "C:\sheet.xlsx";
FileWriter fw = new FileWriter(filePath );
}
catch (IOException e)
{
System.out.println("File is open");
}
I don't think you'll ever get a definitive solution for this, the operating system isn't necessarily going to tell you if the file is open or not.
You might get some mileage out of java.nio.channels.FileLock, although the javadoc is loaded with caveats.
Hi I really hope this helps.
I tried all the options before and none really work on Windows. The only think that helped me accomplish this was trying to move the file. Event to the same place under an ATOMIC_MOVE. If the file is being written by another program or Java thread, this definitely will produce an Exception.
try{
Files.move(Paths.get(currentFile.getPath()),
Paths.get(currentFile.getPath()), StandardCopyOption.ATOMIC_MOVE);
// DO YOUR STUFF HERE SINCE IT IS NOT BEING WRITTEN BY ANOTHER PROGRAM
} catch (Exception e){
// DO NOT WRITE THEN SINCE THE FILE IS BEING WRITTEN BY ANOTHER PROGRAM
}
If file is in use FileOutputStream fileOutputStream = new FileOutputStream(file); returns java.io.FileNotFoundException with 'The process cannot access the file because it is being used by another process' in the exception message.
I'm trying to write an applet for a website that needs access to a system on the LAN, so using a network path (\\THEBOX\DIR\SUBDIR). I'm checking if the directory exists before using it:
try {
File theDir = new File(filepath);
if (!theDir.exists()) theDir.mkdir();
}
catch(Exception e) {
JOptionPane.showMessageDialog(null, e.getCause()+"\n\n"+e.getLocalizedMessage());
}
This catches the exception java.io.FilePermission. The .jar file is signed with a self certificate. Here's the catch- if I run this inside of void init() it works fine, but when I name it void myFunction() the error shows. I need to name it something other than init so it doesn't run on page load and can be called from javascript.
Edit:
As a workaround I'm going to switch back to using init(), but not load the applet until the button is clicked. While I'd prefer the more proper way we can't always be that fortunate.