I'm having some problems with file deletion in Java. I'm doing a simple CRUD application for my OOP class and we need to use files as database. I tried to create a function to erase the database (Delete all database files and save new empty ones), but, so far, I always receive the success message, but the files still there, untouched.
I have the file path set this way in my config.java file:
private String fileBooks = "books.dat";
private String fileUsers = "users.dat";
private String fileOperations = "operations.dat";
I have this function, responsible for file erase:
public void deleteFiles() {
try {
File fbooks = new File(config.getFileBooks());
File fusers = new File(config.getFileUsers());
File fop = new File(config.getFileOperations());
if(fbooks.delete() && fusers.delete() && fop.delete()){
JOptionPane.showMessageDialog(null, "Success!",
"Database cleaning", JOptionPane.PLAIN_MESSAGE);
}else{
JOptionPane.showMessageDialog(null, "Error!",
"Database cleaning", JOptionPane.ERROR_MESSAGE);
}
} catch (Exception e) {
e.printStackTrace();
}
}
I checked the inheritance, the controller, everything looks fine. What I'm doing wrong? Is it a problem with the path?
If is useful information I'm running a Ubuntu 14.04 LTS, using NetBeans to code.
Any help and code advice will be welcome.
EDIT:
I added the System.out.println(fbooks.getAbsoluteFile()) this was my output:
/home/dotk/Dropbox/College/OOP/TP02/hw02/books.dat
/home/dotk/Dropbox/College/OOP/TP02/hw02/users.dat
/home/dotk/Dropbox/College/OOP/TP02/hw02/operations.dat
Do I need to change the path? I want the program to be OS independent, and it will be probably tested in a windows machine.
EDIT 2
I changed the file names, now they don't have the "./" but still not working. I verified that isn't any other open streams to the files, the only ones that run are in the start of the program to load the informations in ArrayLists, but they are closed after.
I found the error, the problem was in the order of the calls. I feel a little bit stupid, but now is fixed.
Related
So right now I´m trying to load an Image on my Harddrive in a BufferdImage in my Code. Yet I think I did everything right but my trycatch only leaves the catch.
Code for better understanding :
private static BufferedImage image;
public void initPictures() {
try {
image = ImageIO.read(new File("Pictures/blue.png"));
} catch (IOException ex) {
System.out.println("Will not load");
ex.printStackTrace();
}
}
The initPictures() is called in my Constructor of the Class. And you can see here that my picture that I try to load is in the E:\Dropbox\Dropbox\Java Projekte\FallingBlocks1\build\classes\Pictures folder on my OS. So the "Pictures/blue.png" should be good.
Windows Folder Picture:
So my Qustion here is : What am I missing?
EDIT : added ex.printStackTrace(); nothing changed thought.
EDIT : also tried to load other pictures int the "image", with no other results
There are two possibilities:
1. Your program may not be running in the folder that contains the "Pictures" folder.
To find out where your program is running, do a System.out.println(System.getProperty("user.dir")); to see what folder you're running in. If it prints something other than E:\Dropbox\Dropbox\Java Projekte\FallingBlocks1\build\classes, you know it's an issue with the path you're providing to ImageIO.read(file). For kicks, you may also want to see what new File("Pictures/blue.png").isFile() is returning.
2. Your image might not readable.
If you try the first test out and you know for certain that the path you are providing is correct, then it's likely that your image file is either corrupt or cannot be read (could be caused by access restrictions, connectivity problems, hardware issues, etc.). Try pointing to a different image and see what happens.
I have servlet, which create html-file and then convert it to pdf-file:
private void ConvertHTMLtoPDF(String sConvertationProgramm, String sHTML, String sPDF)
{
try {
ProcessBuilder pb = new ProcessBuilder(sConvertationProgramm, sHTML, sPDF);
Process process = pb.start();
} catch (Exception e) {
e.printStackTrace();
}
}
Everything work perfect, but then I open this new (as I think) generated pdf-file from this code:
ConvertHTMLtoPDF("C:\\Program Files (x86)\\wkhtmltopdf\\wkhtmltopdf.exe",
"PDFtemplate/requiredPDF.html",
"PDFtemplate/Report.pdf");
response.sendRedirect("PDFtemplate/Report.pdf");
- that gave me previous pdf-file, which was created before.
Furthermore I've tried to open it from Windows explorer, and it's also showed me previous file every first opens.
Does anybody have any suggestion what's happen and how to solve this problem?
Any input would be greatly appreciated,
Thanks
You are doing response.sendRedirect("PDFtemplate/Report.pdf") after starting some process. You should wait finish of that process and only after finishing make other actions.
Use process.waitFor();
Are you sure you are replacing your current file with the new one, I doubt you are writing your new file into this location.
I was willing to make a simple application that stores data in a text file according to this entry but I am facing a frustrating exception.
This is my code:
private boolean saveFile(String fileName, String fileContent) {
DataOutputStream os = null;
FileConnection fconn = null;
try {
fconn = (FileConnection)Connector.open(fileName,Connector.READ_WRITE);
if (!fconn.exists())
fconn.create();
os=fconn.openDataOutputStream();
String myString=fileContent;
os.write(myString.getBytes());
os.close();
fconn.close();
} catch (IOException e) {
// TODO Auto-generated catch block
Dialog.alert(e.toString());
return false;
}
return true;
}
private String getFileName() {
return "file:///SDCard/BlackBerry/documents/text.dat";
}
This is the exception I get:
net.rim.device.api.io.file.FileIOException: File system error
The API says the following:
IOException - if the firewall disallows a connection that is not btspp or comm.
which I don't know if might be helpful or not.
I am using BlackBerry JRE 4.6.1 and a BlackBerry 8900 Simulator.
Hope you guys can help me out.
Check that your simulator has mounted SDCard.
If your is autostart you have to wait until system is completely powered up and SDCard is mounted: example
And the final - you have to close streams and file connection at the end of failed operation also.
Ok, the answer is tricky. I kept trying with the same code over and over until I started to think that it was a problem related to the simulator so what I did is, before running the application, I removed and inserted the SD card using the Options item from the Blackberry interface menu and that was it. It worked like charm. I guess it is a bug in the simulator.
We have several JUnit tests that rely on creating new files and reading them. However there are issues with the files not being created properly. But this fault comes and goes.
This is the code:
#Test
public void test_3() throws Exception {
// Deletes files in tmp test dir
File tempDir = new File(TEST_ROOT, "tmp.dir");
if (tempDir.exists()) {
for (File f : tempDir.listFiles()) {
f.delete();
}
} else {
tempDir.mkdir();
}
File file_1 = new File(tempDir, "file1");
FileWriter out_1 = new FileWriter(file_1);
out_1.append("# File 1");
out_1.close();
File file_2 = new File(tempDir, "file2");
FileWriter out_2 = new FileWriter(file_2);
out_2.append("# File 2");
out_2.close();
File file_3 = new File(tempDir, "fileXXX");
FileWriter out_3 = new FileWriter(file_3);
out_3.append("# File 3");
out_3.close();
....
The fail is that the second file object, file_2, never gets created. Sometimes. Then when we try to write to it a FileNotFoundException is thrown
If we run only this testcase, everything works fine.
If we run this testfile with some ~40 testcases, it can both fail and work depending on the current lunar cycle.
If we run the entire testsuite, consisting of some 10*40 testcases, it always fails.
We have tried
adding sleeps (5sec) after new File, nothing
adding while loop until file_2.exists() is true but the loop never stopped
catching SecurityException, IOException and even throwable when we do the New File(..), but caught nothing.
At one point we got all files to be created, but file_2 was created before file_1 and a test that checked creation time failed.
We've also tried adding file_1.createNewFile() and it always returns true.
So what is going on? How can we make tests that depend on actual files and always be sure they exist?
This has been tested in both java 1.5 and 1.6, also in Windows 7 and Linux. The only difference that can be observed is that sometimes a similar testcase before fails, and sometimes file_1 isn't created instead
Update
We tried a new variation:
File file_2 = new File(tempDir, "file2");
while (!file_2.canRead()) {
Thread.sleep(500);
try {
file_2.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
This results in alot of Exceptions of the type:
java.io.IOException: Access is denied
at java.io.WinNTFileSystem.createFileExclusively(Native Method)
at java.io.File.createNewFile(File.java:883)
... but eventually it works, the file is created.
Are there multiple instances of your program running at once?
Check for any extra instances of javaw.exe running. If multiple programs have handles to the same file at once, things can get very wonky very quickly.
Do you have antivirus software or anything else running that could be getting in the way of file creation/deletion, by handle?
Don't hardcode your file names, use random names. It's the only way to abstract yourself from the various external situations that can occur (multiple access to the same file, permissions, file system error, locking problems, etc...).
One thing for sure: using sleep() or retrying is guaranteed to cause weird errors at some point in the future, avoid doing that.
I did some googling and based on this lucene bug and this board question seems to indicate that there could be an issue with file locking and other processes using the file.
Since we are running this on ClearCase it seems plausible that ClearCase does some indexing or something similar when the files are being created. Adding loops that repeat until the file is readable solved the issue, so we are going with that. Very ugly solution though.
Try File#createTempFile, this at least guarantees you that there are no other files by the same name that would still hold a lock.
I'm building a mobile app with J2ME, and I've found that the data I write into a RecordStore can be accessed while the program is still running but it is lost after quitting and restarting it. No exception is thrown, the data is simply lost.
UPDATE: Thanks everyone for your suggestions. I'm using NetBeans on Windows 7. I'm not sure if it is using the WTK version I have previously installed or another one it has installed somewhere else. I've checked my WTK folder for the files Pavel wrote about, but couldn't find them. Now I'm testing the features requiring persistence on my phone and everything else in the emulator, but it would of course be much better to be able to test everything in the emulator.
private RecordStore recordStore = null;
public MyMIDlet() {
readStuff(); // output: nothing found in recordStore :(
saveStuff();
readStuff(); // output: stuff
}
private void readStuff() {
try {
recordStore = RecordStore.openRecordStore(REC_STORE, true);
int n = recordStore.getNumRecords();
String stuff;
if (n == 0) {
stuff = "nothing found in recordStore :(";
}
else {
stuff = new String(recordStore.getRecord(1));
}
System.out.println(stuff);
}
catch (Exception e) {
System.out.println("Exception occured in readStuff: " + e.getMessage());
}
finally {
if (recordStore != null) {
try {
recordStore.closeRecordStore();
}
catch (Exception e) {
// ignore
}
}
}
}
private void saveStuff() {
try {
recordStore = RecordStore.openRecordStore(REC_STORE, true);
int n = recordStore.getNumRecords();
byte[] stuff = "stuff".getBytes();
recordStore.addRecord(stuff, 0, stuff.length);
} catch (Exception e) {
System.out.println("Exception occured in saveStuff: " + e.getMessage());
} finally {
if (recordStore != null) {
try {
recordStore.closeRecordStore();
} catch (Exception e) {
// ignore
}
}
}
}
If you use Sun WTK, it creates a file named "in.use" in its "appdb" folder:
C:\WTK25\appdb\DefaultColorPhone\in.use
If you close your emulator in unusual way (kill a process, for example), it would not delete it, and next time you run emulator, it would create temporary folder for storing data:
C:\WTK25\appdb\temp.DefaultColorPhone1
when starting this way, it should print in console: "Running with storage root temp.DefaultColorPhone1".
I fix it, including into my ".bat" file a line for deleting "in.use" file each time, emulator runs. But you should be careful when running several emulators at once.
I experienced the same problem myself, I did however discover that NetBeans, or whatever, deletes the deployed program files after execution. These files are located in the C:\Documents and Settings\MyUser\javame-sdk\3.0\work\0\appdb folder, might be different on Vista/Win7 and I guess the number in the path refers to the emulator you are currently using. Anyways, in this folder look for something that is named like your RecordStore. E.g. "00000002_PSC_onfig.db", which is my suite configuration recordstore named PSConfig. By copying this to e.g. "Copy of 00000002_PSC_onfig.db" it will not be deleted. After NetBeans have cleaned up, just copy it back to its original name.
The next time you hit run in NetBeans your recordstore will be there. It's pain, but at least it gives you the possibility to use the emulator to debug your RMS handling.
This question has been around for a while but I stumbled upon it whilst looking for an answer to the same problem with the emulator but in my case it was when using the Java ME 3 SDK. It is possible that the solution I found might also fix this problem.
Using:
emulator -Xdescriptor:/path/to/app.jad
will according to the docs: "Install a MIDlet, run it, and uninstall it after it finishes."
To persist an installation (and it's data) you should use:
emulator -Xjam:install=<JAD-file-URL>
The JAD file URL can either be a web address or 'file:///path/to/app.jad' if you want to install from your local file system. This installation command will display an application storage number which you can then use to launch the emulator and run the previously installed app by calling:
emulator -Xjam:run=<application-storage-number>
See the docs for further command line options.
I could finally get it to work on a real handset. It seems that, as Martin Clayton suggested, the emulator reset erased the data. I'm still looking for a way to enable persistence in the emulator though.
If you are using windows Vista there can and almost are permission issues. I am not sure how to resolve this but you might want to check that the user that is running the emulator has access to write to the emulator store.
In appdb/$phone/*.db
to fix the storage problem you need to check the option "Storage size" in the netbeans platform manager.
Go in project properties;
go in platform;
manage emulators;
select the sun java wireless toolkit;
go in Tools and Extensions;
open preferences;
storage;
storage size option... set a size.
this works for me
I experienced the same issue on Ubuntu Linux and working with WTK 2.5.2 and Netbeans 8.0.2. I later figured it was caused by shutting down my laptop without closing the emulator. It also happens if you run a second emulator without shutting down the first.
My solution is based on the Best Answer here, just shut down all emulators and delete the file located at
~/j2mewtk/2.5.2/appdb/DefaultColorPhone