I'd like to check for an existing file using a while loop. Now the problem is, that if use something like this:
while (file.exists()) {
text.setText("Some text appears");
text.setTextColor(Color.RED);
}
my program always seem to not to respond at all. Is it because my loop is somehow an infinite loop? Or why is is not working correctly.
Right now, i am using a simple if statement but i don't like it that way, because it is not updated right away when the file exists.
EDIT:
What i want is:
I offer a file to download. In my app, there is a text which says "Not Available yet". I want to change the text right after the file exists to something like "File is Available".
If you want to check periodically if a file exists, you have to do this with an asynchronous task or a timer.
TTimerTask task = new TimerTask() {
#Override
public void run() {
// Here you do whatever you want
}
};
Timer timer = new Timer();
timer.schedule(task, 0,30000);
This will check the file every thirty seconds.
You can find more info on http://www.mkyong.com/java/jdk-timer-scheduler-example/
Your program goes in an infinite loop as the condition inside while loop will always be true if the file is present..
You need to check like this:
File file = new File(subDir.getPath() + "somefile.txt");
boolean exists = file.exists();
if (!exists) {
// It returns false if File or directory does not exist
}
else
{
//Update here
}
And if you want to check it inside the loop then try like this:
while (true)
{
File file = new File(subDir.getPath() + "somefile.txt");
boolean exists = file.exists();
if (!exists) {
// It returns false if File or directory does not exist
return;
}
else
{
//Update here
}
}
If the file exists, then it'll pop into the while loop and will keep on looping because the file exists, you'll have to make the file non-existable within the while loop...
Best thing for you to do, is get your program working without the while loop... as you mentioned with an IF function, then slowly over time implement (Test) a new function (while loop) into the equation.
What you need to fix in the while loop is... What happens to the file when it enters the loop and how does it get out of the loop. Current standing is, it doesn't as the file still exists.
Ok so whenever the other person is checking for the file does the program exit if the file doesn't exist? I mean you can't just have it checking for the file forever. I suppose you could put it in a Thread and run it with a slight wait inside the while loop but the overhead... sheesh!
Is this a specific screen inside your program? Is the person suppose to be able to exit this "file found/not found" page? I could probably write a snippet but I need more info. :)
Related
The Below code I was writing , where the element will get store in list , and click randomly using the java random method and after clicking it should print the success message
ISSUE : the Code is getting pass and printing the success message without clicking any web-element
List<WebElement> ev_Collection = driver.findElements(By.xpath("//div[#class='collection-card']");
Random random = new Random();
int index = random.nextInt(ev_Collection.size());
System.out.println("the bound is "+ index) ;
ev_Collection.get(index).click();
System.out.println("Success ");
Do I need to change the above code please let me know
It looks to me like right now there's no conditional for testing if anything was clicked. Rather the code is running sequentially and the last line to be run is a print statement.
Try using a ClickHandler and putting the print statement inside that.
I'm a beginner and can't work out why this loop won't break.
I need to delete some users and for each user i'm prompted if i'm sure i want to delete the user.
so i made the following loop:
while (!alert && delete_button_is_present)
{
clickDeleteBtn;
if(alert)
{
driver.switchTo().alert().accept();
}
else if(delete_button_is_not_present)
{
break;
}
}
Problem is after all users are deleted and delete button is not present anymore the test is still looking for the button.
Make sure delete_button_is_present is or at least can be modified in either clickDeleteButton or driver.switchTo().alert().accept(), or that condition can never be met.
Some questions I have about your code though, which might help if they get cleaned up: you have delete_button_is_present and delete_button_is_not_present. You can get rid of not_present and just use !delete_button_is_present. Why do you have an else if which isn't paired with an if inside if(alert)? If you mean for this to be if(alert), then if(!delete_button_present) then you just need an if statement. Otherwise you want that else if outside the if(alert).
Lets walk through your code
while (!alert && delete_button_is_present)
{
clickDeleteBtn;
if(alert)
{
driver.switchTo().alert().accept();
else if(delete_button_is_not_present)
{
break;
}
}
You're saying that you want to continue this loop as long as there is no alert, and there is a delete button present on the screen. First, you click the delete button. Without any information about what this button does, I'll assume it is not relevant to the loop. You say if(alert), but if there was an alert you wouldn't be in the loop in the first place...So the loop repeats
I'm writting in a file that has the .csv extension . The function that writes in the file is called from a timer that checks continuosly some conditions and updates the file. However, if the user decides to open that file while the timer is running I will obviously get an exception.
Is there a possibility to avoid this and update the file so that the user will see the updated file when reopens the file ?
EDIT:
Timer=new Timer(5000, new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
Display.getDefault().asyncExec(new Runnable(){
#Override
public void run()
{
//Here I check the conditions
checkConditions();
if(checkConditions())
{
writeInFile();
}
}
}
}
EDIT(2):
public void writeInFile()
{
File firstFile=new File("file location");
BufferedWriter out_firstFile = null;
FileWriter firstFileStream;
firstFileStream= new FileWriter(firstFile, false);
out_firstFile = new BufferedWriter(firstFileStream);
out_firstFile.write("Here I write something :) ");
out_firstFile.close();
}
First of all your statement "However, if the user decides to open that file while the timer is running I will obviously get a FileNotFound exception." is absolutely not obvious.
What do you call "open the file". If user opens file using text editor or one of the viewing tools it depends on the tool. For example either less of Unix or Notepad from MS Windows just read the file and do not even lock it. Howerver other tools can lock the file, so you indeed will not be able to write to it, but I think that the exception will be different.
So, I'd change your question to the following "How to write to locked file?".
And the short answer is "you cannot write to the locked file."
The solution that I can suggest is to implement re-try mechanism. If for example you cannot write to file because it is locked at the moment, write your content to temporary file and try again, and again ... and again until you succeed.
What I'm trying to do here is to upload files one by one. For example, if my file list contains 2 files ready to upload, I want to upload the second file once the first is uploaded and created.
Actually, I loop the file list and upload the file from each iteration whitout waiting the last upload to finish.
Here is an idea of what I'm excepecting :
for(FileContainerBean fileContainer:fileContainerList){
FileUpload fileUpload=new FileUpload(fileContainer.getFile());
Thread th=new Thread(fileUpload);
th.start();
//Now i want here to wait beafore moving to the next iteration
while(!fileContainer.isCreated(){
wait();
}
if(fileContainer.isCreated(){
notify();
}
}
fileContainer is a bean with getters and setters (setFile,getFile,isCreated....).
When the upload is over and the file is created ( HttpResponseCode=201), fileContainer.isCreated=true. Initially, isCreated=false;
I hope that I'm clear enough ! So is it possible to do that ?
Thanks in advance !
Ismail
So you basically want to continue the execution only after the th thread is finished? Just don't run it in a separate thread, but rather:
for(FileContainerBean fileContainer:fileContainerList){
FileUpload fileUpload=new FileUpload(fileContainer.getFile());
fileUpload.run();
// continues after the file is uploaded
}
If you want to keep this in a separate thread after all (as you said in a comment), then execute the whole loop in the background:
Runnable uploadJob = new Runnable() {
public void run() {
for(FileContainerBean fileContainer:fileContainerList){
FileUpload fileUpload=new FileUpload(fileContainer.getFile());
fileUpload.run();
// continues after the file is uploaded
}
}
};
new Thread(uploadJob).start();
You should set the notify() in the run method of Thread th so after the new thread finish the upload, it will notify the waited thread.
Or I see that you want your main thread to wait until the upload process completed, so why don't you simply make your program single threaded.
I mean don't initiate the upload process in a new thread, because the default behavior then is wait until the current upload is finished then start the second upload and that is what you want.
Do like this
while(true){
if(fileContainer.isCreated()){
break;
}
}
In my j2me application i have to play a small sound file each times user click on an item. But the issues is when i play sound file multiple times like after 10-14 times it gives me
out of memory exception. Although i release the player each time i play the file but still it
gives out of memory exception : Here is the code snippet,
public void playSound(String soundFile) {
try{
if (player!=null) {
try {
player.deallocate(); //deallocate the unnecessary memory.
} catch (Exception ex) {
player=null;
System.gc();
}
}
player = Manager.createPlayer(getClass().getResourceAsStream(musicFolder + soundFile), "audio/mpeg");
// player = Manager.createPlayer(is, "audio/mpeg");
player.realize();
// get volume control for player and set volume to max
VolumeControl vc = (VolumeControl) player.getControl("VolumeControl");
if (vc != null) {
vc.setLevel(100);
}
player.prefetch();
player.start();
isException=false;
} catch (Exception e) {
isException=true;
}
}
Can someone tell me what is going wrong?
3 things to keep in mind
If you are going to play the same sound several times, you might want to keep one Player prefetched and simply start it multiple times.
When you want to properly cleanup a player, you should call Player.close()
You may want to use a media event listener to close and/or restart a player independently of user input.
I think you should also call
player.close()
right after after
player.deallocate();
According to documentation "When deallocate returns, the Player is in the UNREALIZED or REALIZED state." but close goes further... "When the method returns, the Player is in the CLOSED state and can no longer be used."
I'm not sure why the de-allocation isn't working. I guess it either takes longer to de-allocated than to create a new one, or the de-allocation fails for some reason. Is there a player.stop() to match the player.start()?
Another thing to try (if nothing else, for good form :) is not to create new player unless you need to/should. I.e. move the
if(player!=null){
So it also covers
player = Manager.createPlayer(getClass().getResourceAsStream(musicFolder + soundFile), "audio/mpeg");
HTH!