Why my "Save" button doesn't work? - java

I have one of the biggest problem in my program. I've created Save button, but it saves if the .txt file is new (Then that button does "SaveAs" function). But when I open file, then type something and trying to save and it's not saving :S. Can anyone help me?
Here's the code:
fileSave.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(currentFile == null) {
int saveResult = fileSelect.showSaveDialog(null);
if(saveResult == fileSelect.APPROVE_OPTION) {
saveFile(fileSelect.getSelectedFile(), field.getText());
} else {
saveFile(currentFile, field.getText());
}
}
}
});
public void saveFile(File file, String contents) {
BufferedWriter writer = null;
String filePath = file.getPath();
if(!filePath.endsWith(".txt")) {
filePath += ".txt";
}
try {
writer = new BufferedWriter(new FileWriter(filePath));
writer.write(contents);
writer.close();
field.setText(contents);
setTitle("Editex - " + filePath);
currentFile = file;
} catch (Exception e) {
}
}

You aren't handling when currentFile != null, which is what I am assuming is the case when you are trying to save a file that already has a Filename.
Do something like this:
if(currentFile == null) {
// Handle if new file
} else {
// Handle an existing file
}
Move
saveFile(currentFile, field.getText());
into the else part of the above if else.
At the moment you have it within the if(currentFile == null), and this isn't the correct place as you are calling saveFile(null, field.getText()) here.
Also
catch(Exception e) {
}
is bad, never swallow an exception and do nothing with it, you will never know if an exception happens or not, just nothing will happen.

Related

How can I resume code where I left off after FILENOTFOUNDEXCEPTION is thrown

I am writing a file into a directory. There might be the chance that the directory becomes unreachable.
What I want to do is..
As the code is writing to the file, if the directory becomes unreachable or a file not found exception is thrown I want it to keep checking if the directory exists and continue where I left off after the directory exists again.
After some time if the directory does not come back up then I would shut the program down.
My problem is that when a file not found exception is thrown the program just shuts down all together. Here is my code:
public class BusStopsProcessor implements Runnable
{
private BlockingQueue<Bus<buses>> busQueue;
private Bus<buses> BusObject;
public BusStopsProcessor(BlockingQueue<Bus<buses>> busQueue)
{
this.busQueue = busQueue;
}
#Override
public void run()
{
try
{
String path = "C:\\Users\\Me\\Documents\\";
File file = new File(path + "busStopsFile.txt");
FileWriter fw = new FileWriter(file, true);
CSVWriter writer = new CSVWriter(fw, '|', CSVWriter.NO_QUOTE_CHARACTER);
while(true)
{
BusObject = busQueue.take();
//each bus object should have a bus date if it does not then it is a
//poison bus object.
if(BusObject.getBusDate() != null)
{
createBusFile(BusObject, writer);
else
{
try
{
//Finished processing bus stops so close writer.
writer.close();
fw.close();
break;
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
}
catch (InterruptedException e)
{
Thread.currentThread().interrupt();
e.printStackTrace();
}
catch (FileNotFoundException e)
{
//If a FILENOTFOUND exception is thrown here I want
//my code to be able to pick up where I left off
e.printStackTrace();
logger.warn(e.getMessage());
}
catch (IOException e)
{
e.printStackTrace();
}
}
Here is the method that I want to keep checking if the directory exists. If the file is being written into and all of a sudden the directory goes down. I dont want to repeat the same information in the file I want it to continue to write from where it left off but I just cant figure out how to do that. thank you.
private void createBusFile(Bus<buses> aBusObject, CSVWriter writer) throws InterruptedException
{
//Get bus information here
for(Bus<buses> busStop : aBusObject.getBusStops())
{
busNumber = busStop.getBusNumber();
busArrivalTime = busStop.getBusArrivalTime();
busStop = busStop.getBusStop();
String[] busFields = {busNumber, busDate, busStop};
//If a file not found exception is thrown here I want it to keep checking if the directory exists. And pick up from where I left off
writer.writeNext(busFields);
}
}
}

Csv file is empty when I writing content

I am trying write to a csv file. After the execution of the code bellow the csv file is still empty.
File is in folder .../webapp/resources/.
This is my dao class:
public class UserDaoImpl implements UserDao {
private Resource cvsFile;
public void setCvsFile(Resource cvsFile) {
this.cvsFile = cvsFile;
}
#Override
public void createUser(User user) {
String userPropertiesAsString = user.getId() + "," + user.getName()
+ "," + user.getSurname() +"\n";;
System.out.println(cvsFile.getFilename());
FileWriter outputStream = null;
try {
outputStream = new FileWriter(cvsFile.getFile());
outputStream.append(userPropertiesAsString);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
#Override
public List<User> getAll() {
return null;
}
}
This is a part of beans.xml.
<bean id="userDao" class="pl.project.dao.UserDaoImpl"
p:cvsFile="/resources/users.cvs"/>
Program compiles and doesn't throw any exceptions but CSV file is empty.
If you're running your app in IDE, the /webapp/resources used for running app will differ from the /webapp/resources in your IDE. Try to log full path to file and check there.
try using outputStream.flush() as the final statement in the first of the try block.
I think you're looking at the wrong file. If you specify an absolute path /resources/users.cvs, then it probably won't be written into the a folder relative to the webapp. Instead, it will be written to /resources/users.cvs
So the first step is to always log an absolute path to make sure the file is where you expect it.
Try with this code, it will at least tell you where the problem lies (Java 7+):
// Why doesn't this method throw an IOException?
#Override
public void createUser(final User user)
{
final String s = String.format("%s,%s,%s",
Objects.requireNonNull(user).getId(),
user.getName(), user.getSurname()
);
// Note: supposes that .getFile() returns a File object
final Path path = csvFile.getFile().toPath().toAbsolutePath();
final Path csv;
// Note: this supposes that the CSV is supposed to exist!
try {
csv = path.toRealPath();
} catch (IOException e) {
throw new RuntimeException("cannot locate CSV " + path, e);
}
try (
// Note: default is to TRUNCATE the destination.
// If you want to append, add StandardOpenOption.APPEND.
// See javadoc for more details.
final BufferedWriter writer = Files.newBufferedWriter(csv,
StandardCharsets.UTF_8);
) {
writer.write(s);
writer.newLine();
writer.flush();
} catch (IOException e) {
throw new RuntimeException("write failure", e);
}
}

file.delete() wont delete file, java

Okay, this is going to be a bit long. So I made a junit test class to test my program. I wanted to test if a method that uses a Scanner to read a file into the program threw and exception, if the file didn't exist like this:
#Test
public void testLoadAsTextFileNotFound()
{
File fileToDelete = new File("StoredWebPage.txt");
if(fileToDelete.delete()==false) {
System.out.println("testLoadAsTextFileNotFound - failed");
fail("Could not delete file");
}
try{
assertTrue(tester.loadAsText() == 1);
System.out.println("testLoadAsTextFileNotFound - passed");
} catch(AssertionError e) {
System.out.println("testLoadAsTextFileNotFound - failed");
fail("Did not catch Exception");
}
}
But the test fails at "could not delete file", so I did some searching. The path is correct, I have permissions to the file because the program made it in the first place. So the only other option would be, that a stream to or from the file is still running. So I checked the method, and the other method that uses the file, and as far as I can, both streams are closed inside the methods.
protected String storedSite; //an instance variable
/**
* Store the instance variable as text in a file
*/
public void storeAsText()
{
PrintStream fileOut = null;
try{
File file = new File("StoredWebPage.txt");
if (!file.exists()) {
file.createNewFile();
}
fileOut = new PrintStream("StoredWebPage.txt");
fileOut.print(storedSite);
fileOut.flush();
fileOut.close();
} catch(Exception e) {
if(e instanceof FileNotFoundException) {
System.out.println("File not found");
}
fileOut.close();
} finally {
if(fileOut != null)
fileOut.close();
}
}
/**
* Loads the file into the program
*/
public int loadAsText()
{
storedSite = ""; //cleansing storedSite before new webpage is stored
Scanner fileLoader = null;
try {
fileLoader = new Scanner(new File("StoredWebPage.txt"));
String inputLine;
while((inputLine = fileLoader.nextLine()) != null)
storedSite = storedSite+inputLine;
fileLoader.close();
} catch(Exception e) {
if(e instanceof FileNotFoundException) {
System.out.println("File not found");
return 1;
}
System.out.println("an Exception was caught");
fileLoader.close();
} finally {
if(fileLoader!=null)
fileLoader.close();
}
return 0; //return value is for testing purposes only
}
I'm out of ideas. Why can't I delete my file?
EDIT: i've edited the code, but still this give me the same problem :S
You have two problems here. The first is that if an exception is thrown during your write to the file, the output stream is not closed (same for the read):
try {
OutputStream someOutput = /* a new stream */;
/* write */
someOutput.close();
The second problem is that if there's an exception you aren't notified:
} catch (Exception e) {
if (e instanceof FileNotFoundException) {
/* do something */
}
/* else eat it */
}
So the problem is almost certainly that some other exception is being thrown and you don't know about it.
The 'correct' idiom to close a stream is the following:
OutputStream someOutput = null;
try {
someOutput = /* a new stream */;
/* write */
} catch (Exception e) {
/* and do something with ALL exceptions */
} finally {
if (someOutput != null) someOutput.close();
}
Or in Java 7 you can use try-with-resources.

Saving file java

Because the File object constructor needs a String to represent the path and considering other reasons, I chose to make a temporary file and when the user wants to save, to take the content of the temporary to the final file and ask the user to give the path at that time.
I have some code I will explain, but for many reasons, I think it's not one of the best solutions to do what I am trying to do.
public String FileSavePath() throws NullPointerException {
boolean acceptable = false;
String theFilepath = null;
do {
theFilepath = null;
File f = null;
JFileChooser FileChooser = new JFileChooser();
if (FileChooser.showSaveDialog(null) == JFileChooser.APPROVE_OPTION) {
theFilepath = FileChooser.getSelectedFile().getAbsolutePath();
f = FileChooser.getSelectedFile();
//System.out.println(theFile);
if (f.exists()) {
int result = JOptionPane.showConfirmDialog(this, "The file exists, overwrite?",
"Existing file", JOptionPane.YES_NO_CANCEL_OPTION);
if (result == JOptionPane.YES_OPTION) {
acceptable = true;
}
}
} else {
acceptable = true;
}
} while (!acceptable);
saved=true;
return theFilepath;
}
And the method is called in the save function this way:
FileChannel sourceChannel=null;
FileChannel targetChannel=null;
try
{
try{
file=new File(FileSavePath());
}
catch(NullPointerException npe)
{
System.exit(0);
}
sourceChannel = new FileInputStream(temp).getChannel();
targetChannel = new FileOutputStream(file).getChannel();
targetChannel.transferFrom(sourceChannel, 0,
sourceChannel.size());
}
catch(IOException ioe)
{
System.out.println(ioe.getMessage());
}
finally
{
try {
if (sourceChannel != null) {
sourceChannel.close();
}
if (targetChannel != null) {
targetChannel.close();
}
} catch (IOException e1) {
e1.printStackTrace();
}
}
Basically the mechanism is the following: All the data is saved to a temporary file. When the user wants to save, a JFileChooser appears and saves the path. Then the final file is iniatialized, the temporary data passed to the final file and that's it. The NPE is important to handle if the user did not chose a valid path or cancelled somewhere during the
What I am not sure of is if my code is efficent or if there were any ways to make it better.
P.S. Please don't bother telling that the exceptions are not handled yet, I know this, but I want to know if the basic idea would efficently do what is should.

Java continue executing loop if exception was throwd

Example: say I want to open a file. If I get a FileNotFoundException, I need to wait for some time and try again. How can I gracefully do that? Or do I need to use nested try/catch blocks?
Example :
public void openFile() {
File file = null;
try {
file = new <....>
} catch(FileNotFoundException e) {
}
return file;
}
You could use a do { ... } while (file == null) construct.
File file = null;
do {
try {
file = new <....>
} catch(FileNotFoundException e) {
// Wait for some time.
}
} while (file == null);
return file;
public File openFile() {
File file = null;
while (file == null) {
try {
file = new <....>
} catch(FileNotFoundException e) {
// Thread.sleep(waitingTime) or what you want to do
}
}
return file;
}
Note that this is a somewhat dangerous method, since there is no way to break out unless the file eventually appears. You could add a counter and give up after a certain number of tries, eg:
while (file == null) {
...
if (tries++ > MAX_TRIES) {
break;
}
}
public File openFile() {
File file = null;
while(true){
try {
file = new <....>
} catch(FileNotFoundException e) {
//wait for sometime
}
if(file!=null){
break;
}
}
return file;
}

Categories

Resources