I would like to save number to a file when element is displayed and then test should be passed.
Else if element is not visible test should be also passed but number shoudn't be save into a file.
Saving number when element is displayed works fine, also when element is not displayed test don't save it into file so this also works fine.
Two problems:
Selenium search for element when is not displayed approx... 15s? It's too long, how to reduce this time? Use Waits?
Most important, if element is not displayed test fails, I'd like to pass it because the whole process is done and waiting for this element and saving number is additional thing.
public void saveNumberIntoFile(String fileNumber) throws IOException {
if(messageInfo.isDisplayed())
{BufferedWriter writer = new BufferedWriter(
new FileWriter("C:\\Users\\xxx\\Documents\\samplefile.txt", true) //Set true for append mode
);
writer.newLine(); //Add new line
writer.write(fileNumber);
writer.close();}
}
You need WebDriverWait and ExpectedConditions to handle wait element, like this:
new WebDriverWait(driver, 15).until(ExpectedConditions.visibilityOfElementLocated(By.name("")));
Replace By.name("") with the locator that you initialed on messageInfo.
15 in seconds, if the element is located it will not wait until 15s.
But if within a certain time period that we have determined the element is not found, it will return an error:
NoSuchElementException: Cannot locate an element using....
And your test will stop, so you need handle with try/catch.
public void saveNumberIntoFile(String fileNumber) throws IOException {
try {
new WebDriverWait(driver, 15).until(ExpectedConditions.visibilityOfElementLocated(By.name("")));
BufferedWriter writer = new BufferedWriter(
new FileWriter("C:\\Users\\xxx\\Documents\\samplefile.txt", true) //Set true for append mode
);
writer.newLine(); //Add new line
writer.write(fileNumber);
writer.close();
} catch (NoSuchElementException e) {
// TODO: handle exception
}
}
Related
I need to check for a error log file for certain time after starting a process. Either the word found or the timeout reached, I need to exit informing the text is found or Text is not found until the timeout. I tried like below but couldnt achieve
public void waitFortext(String expectedText,
String filePath){
long timeout = 50000 + System.currentTimeMillis();
File file = new File(filePath);
String content = FileUtils.readFileToString(file, "UTF-8");
boolean available = false;
while (available || System.currentTimeMillis() > timeout) {
available = content.contains(expectedText);
Thread.sleep(500);
if (available) {
return;
}
}
}`
Make a variable oldTime and set it to System.nanoTime when you want the time to start. Make a variable newTime and update it to System.nanoTime in every time the code loops. Compare the difference of these two values to your wanted amount of time, exiting the loop when the difference is greater.
The problem here is you read file only once.
Move line
String content = FileUtils.readFileToString(file, "UTF-8");
inside loop (make it first statement.
So everytime someone clicks sign up on my program, I call a method that opens file and adds record.
This is to open the file:
try {
l = new Formatter("chineses.txt");
System.out.println("Did create");
} catch (Exception e){
System.out.println("Did not create");
}
public void addRecord(){ //This is how i add the record
l.format("%s", nameField.getText());
}
Everytime I put in a name in the name field and click sign up in my gui, it always replaces whatever is on the first line in the text file.
How can I make it go to the second line while retaining what is on the first line each time someone else puts their name and clicks sign up?
You just need to create the object of FileWriter and pass it to the Formatter. It will append your text in the File.
Try this code:
FileWriter writer = new FileWriter("chineses.txt",true);
l = new Formatter(writer);
public void addRecord(){ //This is how i add the record
l.format("%s\n", nameField.getText());
}
So, I have a "Memory Game", you can input your name, choose the difficulty(4x4 or a 6x6 game) and then start the game.
When you click Start, a new Panel will pop up and the game will start.
The buttons will be randomized and for each mistake you make, you lose 2 points and for every right combination, you gain 10 points.
At the end or if you click on the Exit button, a message will pop up stating the Player's Name, how many tries he did(clicked 2 different buttons) and how many Points he has. Then the game ends and it doesn't save the Player's Score.
Now, my problem is, I don't know how to implement a Ranking System in my code. It would be something basic, like, a comparison between all the Scores and rearrange them to the one with the most points comes first and so on.
So from what I researched, I would need a Save method that whenever someone finishes a game it would save their scores in a .txt file and an Array method that would arrange the scores form Best to Worst.
Here's the whole code;
http://pastebin.com/6Wtiju7z
private void mostrarResumoJogo() {
resumoJogo = "Jogador: " + objJogadorJogada.getNome() + " " +
"Pontos: " + objJogadorJogada.getPontos() + " " +
"Quantidade de tentativas: " + qtdeTentativas;
JOptionPane.showMessageDialog( null, "" + resumoJogo, "Resumo do Jogo",
JOptionPane.INFORMATION_MESSAGE );
BufferedWriter writer = null;
try {
writer = new BufferedWriter( new FileWriter("Ranking.txt") );
writer.write(resumoJogo);
}
catch ( IOException e) { }
finally {
try {
if (writer != null)
writer.close( );
}
catch ( IOException e) { }
}
setVisible( false );
}
The problem is that the file is always overwritten with a new .txt
I already tried to create a type File attribute so that he doesn't always create another .txt but with no success.
It's the last thing that I need to do on this code, but I can't seem to figure it out, please, help.
The problem is that the file is always overwritten with a new .txt
Problem is here
writer = new BufferedWriter( new FileWriter( "Ranking.txt"));
Each time you invoke new FileWriter( "Ranking.txt") it creates new empty file. If you want to add more data to already existing file you need to open it in append mode via
writer = new BufferedWriter( new FileWriter( "Ranking.txt", true));
// add this part -^^^^
Probably this is what are you looking for
https://docs.oracle.com/javase/7/docs/api/java/io/FileWriter.html#FileWriter(java.lang.String,%20boolean)
Just specify APPEND parameter as true and your changes won't be overwritten
To make it not overwrite, but append instead pass append=true when calling the FileWriter constructor.
Instead of doing that though I would recommend just reading and writing the whole file every time. This is because the scores have to be sorted and rewritten to the file.
I would recommend using JAXB to create an XML file. Here is a tutorial for using JAXB to do this: http://www.mkyong.com/java/jaxb-hello-world-example/
Hi I am writing some data to a text file through java code but when i again run the code its again appending to the older data ,i want the new data to overwrite the older version.
can any one help..
BufferedWriter out1 = new BufferedWriter(new FileWriter("inValues.txt" , true));
for(String key: inout.keySet())
{
String val = inout.get(key);
out1.write(key+" , "+val+"\n");
}
out1.close();
code would help, but its likely you are telling it to append the data since the default is to overwrite. find something like:
file = new FileWriter("outfile.txt", true);
and change it to
file = new FileWriter("outfile.txt", false);
or just
file = new FileWriter("outfile.txt");
since the default is to overwrite, either should work.
based on your edit just change the true to false, or remove it, in the FileWriter. The 2nd parameter is not required and when true specifies that you want to append data to the file.
You mentioned a problem of incomplete writes... BufferedWriter() isn't required, if your file is smallish then you can use FileWriter() by itself and avoid any such issues. If you do use BufferedWriter() you need to .flush() it before you .close() it.
BufferedWriter out1 = new BufferedWriter(new FileWriter("inValues.txt"));
for(String key: inout.keySet())
{
String val = inout.get(key);
out1.write(key+" , "+val+"\n");
}
out1.flush();
out1.close();
Set append parameter to false
new FileWriter(yourFileLocation,false);
You can use simple File and FileWriter Class.
The Constructor of FileWrite Class provides 2 different varieties to make a file. One which only takes the Object of file. and another is with two parameters one with file object and second is boolean true/false which indicates whether file to be created is going to be append the contents or overwriting.
following code will do the overwriting of content.
public class WriteFile {
public static void main(String[] args) throws IOException {
File file= new File("new.txt");
FileWriter fw=new FileWriter(file,true);
try {
fw.write("This is first line");
fw.write("This is second line");
fw.write("This is third line");
fw.write("This is fourth line");
fw.write("This is fifth line");
fw.write("hello");
} catch (Exception e) {
} finally {
fw.flush();
fw.close();
}
}
}
It works same with PrintWriter class also, since it also provides 2 different varieties of Constructors same as FileWriter. But you can always refer to Java Doc API.
I've tried using BufferWriter format as well as FileWriter and PrintWriter each with a boolean true statement but they both behave the same as if I simply used a simple new File. Each time I get to the end of my program run, I call the function that writes the saved data to be appended. What ends up happening is that it overwrites the last saved data. I also have other code blocks that handle that text file as well and reformating them did nothing either.
//saves user information to "Users.txt" which will be called in the finally block after choice switch
public void writeUsers()
{
try{
File userFile = new File("Users.txt");
PrintWriter output = new PrintWriter(userFile);
for(User i: userList) {
output.append("Name:");
output.println(i.getrealName());
output.append("UID:");
output.println(i.getidName());
output.append("Password:");
output.println(i.getpassword());
output.println(" ");
}
output.close();
System.out.print("Information has been saved to Users.txt\n");
}
catch(FileNotFoundException fnf) {
System.err.println("FileNotFoundException: File Users.txt does not exist " + fnf);
}
catch(IOException eyeoh) {
System.err.println("IOException: Error writing to Users.txt " + eyeoh);
}
}
The constructor PrintWriter(File) truncates the output file by default. The fact that PrintWriter's method append() is called doesn't mean that it changes the mode of the file being opened. The behavior for append is described as:
An invocation of this method of the form out.append(csq) behaves in exactly the same way as the invocation
out.write(csq.toString())
Here, you could use the constructor for PrintWriter that takes a FileOutputStream for appending
PrintWriter output =
new PrintWriter(new FileOutputStream(userFile, true /* append = true */));
You have to create the PrintWriter in append mode. Otherwise, when it first opens the file, it will clear it out. You can open it in append mode using:
new PrintWriter(new FileWriter(userFile,true)) // the `true` argument opens it in append mode
PrintWriter by defualt truncates all existing data. To append you could, as other answers suggest, add a "true" argument to the constructor, which denotes "append = true,"
However, this is done more elegantly using java.nio.file.Files along with java.nio.file.StandardOpenOption, in which you can specify StandardOpenOption.APPEND as opposed to StandardOpenOption.TRUNCATE_EXISTING
You can also specify things such as StandardOpenOption.CREATE which creates the file if it does not exist.
Additionally, remember to either place your output.close() statement in a finally block, or use try-with-resources. Otherwise if the flow of the program is interrupted (i.e. an Exception is thrown), output would remain unclosed. I personally use try-with-resources as it is less of a hassle: just declare all your resources, and they are closed automatically for you, whether or not the flow of the program is disrupted.
Also, as a general tip, print or pass the actual Exception object in your catch block, as opposed to just a "custom string" so as to not lose the original content of the Exception thrown. You can then concatenated that with whatever string you also want to print.
try(BufferedWriter bufWriter =
Files.newBufferedWriter(Paths.get("Users.txt"),
Charset.forName("UTF8"),
StandardOpenOption.WRITE,
StandardOpenOption.APPEND, //Makes this BufferedWriter append to the file, not truncate
StandardOpenOption.CREATE);
PrintWriter output = new PrintWriter(bufWriter, true);)
{
output.println("Text to be appended.");
}catch(FileNotFoundException e){
System.err.println(e + "Custom string");
}catch(IOException e){
System.err.println(e + "Something eyeoh occurred...");
}
This uses a try-with-resources statement to declare and create a BufferedWriter using java.nio.file.Files, which accepts StandardOpenOption parameters, and an auto-flushing PrintWriter (denoted by "true" in the constructor) from the resultant BufferedWriter. PrintWriter's println() method, can then be called to write to the file.
The StandardOpenOption parameters used in this code: opens the file for writing, only appends to the file, and creates the file if it does not exist.
Paths.get("path here") can be replaced with new File("path here").toPath(), if you are working exclusively with File objects (i.e. if you are using JFileChooser.getSelectedFile())
And Charset.forName("charset name") can be modified to accommodate the desired Charset.