So I'm trying to add text to a txt file, I have succeeded in doing this, the user is prompted about what they would like to add and it is included when I open the txt file after running my program.
Now, here's my problem: The first time I try to add something to the txt file, it creates a blank row and under that it will have the information the user has added, the reason for this is because when Java opens my file, the typing cursor is on the bottom of the last line, where there is no space and it is ready to enter information, like this:
Alright, cool, so this means whenever I add anything to the txt file from my Java program, it will automatically be on a new line and I will not need to add any println spacing to enter a new line. Now here's where another problem concurs, after Java puts the new text into the txt file, it leaves the typing cursor at the END of the new line added, not at the new line under it where there is no data. So this means if I try to add new information twice, it will appear on the same line and not a new one. So to fix this, I simply added a
pw.println();
statement at the start of my print writer to ensure it puts the cursor on the new line. But now, when i try to add data for the first time again after adding that last line of code, it will create a empty space between the last line of data and the new line of data I have added. Like so:
Now, whenever the user wants to search through the database, because I have null checks in my searches, whenever the program comes across that empty line between my original data and the new data that has been added, It will not continue the search, therefore any information that the user has added to the database is rendered useless and Java won't be able to search for it because of the empty line that separates it.
Basically, either I keep the pw.println() and have all my data come up but have a space inbetween the original data so It can't be searched for, OR i can remove it and then all new data that is added appears on the same line, which is not what I want.
This is the code for adding data to the txt file:
public static void add() throws IOException
{
String filename="Elements.txt";
PrintWriter pw = new PrintWriter(new FileWriter(filename,true));
pw.println();
String element=JOptionPane.showInputDialog(null, "Enter name of element.", "Add an Element", JOptionPane.INFORMATION_MESSAGE);;
pw.write(element + ",");
String symbol=JOptionPane.showInputDialog(null, "Enter symbol of element.", "Add an Element", JOptionPane.INFORMATION_MESSAGE);;
pw.write(symbol + ",");
String atomicNumber=JOptionPane.showInputDialog(null, "Enter atomic number.", "Add an Element", JOptionPane.INFORMATION_MESSAGE);;
pw.write(atomicNumber + ",");
String atomicMass=JOptionPane.showInputDialog(null, "Enter atomic mass", "Add an Element", JOptionPane.INFORMATION_MESSAGE);;
pw.write(atomicMass + ",");
String valence=JOptionPane.showInputDialog(null, "Enter # of valence electrons.", "Add an Element", JOptionPane.INFORMATION_MESSAGE);;
pw.write(valence);
pw.close();
}
Is there any way I can manipulate the cursor on the txt file to ensure that all new data added shows up properly so the user can search for it afterwards? Opening up the txt file and placing the cursor where I want to didn't work.
The idea is to do println() (which adds a line end) at the end of writing whatever should be on a line. If you println() before any other data, it will very likely create an empty line (unless the last line is without a line end).
String filename="Elements.txt";
PrintWriter pw = new PrintWriter(new FileWriter(filename,true));
String element= ... ;
pw.write(element + ",");
// ... more ...
String valence=...;
pw.write(valence);
pw.println();
pw.close();
Related
Basically, I have a jFrame where some data is supposed to show inside whenever I press a button. The data is being taken from different files and the way I want it to work is whenever I press the same button for a file to show me different lines, however it always shows the last line of the file. I would like to add that I am also using a Tokenizer, even though I'm not sure if it is relevant.
I've tried using loops and numbering the lines but it doesn't really work.
private void jButton5ActionPerformed(java.awt.event.ActionEvent evt) {
//Stoke
//Protocol - 555
String fileName="Stoke.txt";
int lineNumber=0;
try
{
FileReader fin=new FileReader(fileName);
BufferedReader din=new BufferedReader(fin);
System.out.println("Data in the file "+fileName+" is ");
//read from the file
String line=null; //line of text
while((line=din.readLine())!=null && lineNumber<1){
//here we have read in a line of text
//now parase line to extract data and print it out to the screen
StringTokenizer st=new StringTokenizer(line,",");
String location=st.nextToken().trim();
String gps=st.nextToken().trim();
String humidity=st.nextToken().trim();
String temperature=st.nextToken().trim();
String dateNtime=st.nextToken().trim();
weatherTable.setText(location+"\n"+gps+"\n"+humidity+"\n"+temperature+"\n"+dateNtime+"\n");
}
din.close(); //close the stream
I am expecting the application to show different lines whenever i press jButton5 but it always shows the last line of the file.
You set lineNumber to 0 initially, and never update it...
but you use it in your while loop condition as lineNumber<1, which means the condition is never failing, until you reach the end of the file, where (line=din.readLine())!=null returns false, and you exit with the last line in the buffer.
You have to figure out a way to count lines, then randomize on [0..numberOfLines] if you want to ouput a random line only, or append instead of set on
weatherTable.setText(location+"\n"+gps+"\n"+humidity+"\n"+temperature+"\n"+dateNtime+"\n");
if you want the entire file to be set.
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/
I have written a method in Java to delete a caret at the end of each line of a file. The method is as follows:
//Creates a new file, and deletes the temp file
public void createFinalFile() throws FileNotFoundException, IOException{
// read file data into a String
String data1 = new Scanner(new File(fileDirectoryString + "tempFile.txt")).useDelimiter("\\Z").next();
// replace all ^ from end of line using (?m) - MULTILINE switch
data1 = data1.replaceAll("(?m)\\^$", "");
PrintWriter docketFile3 = new PrintWriter(new FileWriter(fileDirectoryString + "Forclosure-Docket-"+startingYear+startingMonth+startingDay+"-"+endingYear+endingMonth+endingDay+".txt", true));
docketFile3.write(data1);
}
The issue is that sometimes the temp file will have all the information, but after the method is run the newly created file is blank and I am not sure why. An example of the temp file is:
04/02/2014^BR-12-005193^09/12/2012^P1^SF^DEPOSIT AMOUNT PAID CUYAHOGA COUNTY SHERIFF^
04/02/2014^BR-12-005193^09/12/2012^P1^CS^COST PAYMENT $860.90 CUYAHOGA COUNTY SHERIFF^
While it should just delete the caret at the end of each line, it seems to be deleting every line.
Your regular expression is not what's doing this. Though the function overall reminds me more of this than anything else, it should work. The one thing though that could be going wrong is that you aren't closing your output file. Add docketFile3.close(); as a line after you write the data out.
How do i append an existing line in a text file? What if the line to be edited is in the middle of the file? Please kindly offer a suggestion, given the following code.
Have went through & tried the following:
How to add a new line of text to an existing file in Java?
How to append existing line within a java text file
My code:
filePath = new File("").getAbsolutePath();
BufferedReader reader = new BufferedReader(new FileReader(filePath + "/src/DBTextFiles/Customer.txt"));
try
{
String line = null;
while ((line = reader.readLine()) != null)
{
if (!(line.startsWith("*")))
{
//System.out.println(line);
//check if target customer exists, via 2 fields - customer name, contact number
if ((line.equals(customername)) && (reader.readLine().equals(String.valueOf(customermobilenumber))))
{
System.out.println ("\nWelcome (Existing User) " + line + "!");
//w target customer, alter total number of bookings # 5th line of 'Customer.txt', by reading lines sequentially
reader.readLine();
reader.readLine();
int total_no_of_bookings = Integer.valueOf(reader.readLine());
System.out.println (total_no_of_bookings);
reader.close();
valid = true;
//append total number of bookings (5th line) of target customer # 'Customer.txt'
try {
BufferedWriter writer = new BufferedWriter(new FileWriter(new File(filePath + "/src/DBTextFiles/Customer.txt")));
writer.write(total_no_of_bookings + 1);
//writer.write("\n");
writer.close();
}
catch (IOException ex)
{
ex.printStackTrace();
}
//finally
// {
//writer.close();
//}
}
}
}
To be able to append content to an existing file you need to open it in append mode. For example using FileWriter(String fileName, boolean append) and passing true as second parameter.
If the line is in the middle then you need to read the entire file into memory and then write it back when all editing was done.
This might be workable for small files but if your files are too big, then I would suggest to write the actual content and the edited content into a temp file, when done delete the old one an rename the temp file to be the same name as the old one.
The reader.readLine() method increments a line each time it is called. I am not sure if this is intended in your program, but you may want to store the reader.readline() as a String so it is only called once.
To append a line in the middle of the text file I believe you will have to re-write the text file up to the point at which you wish to append the line, then proceed to write the rest of the file. This could possibly be achieved by storing the whole file in a String array, then writing up to a certain point.
Example of writing:
BufferedWriter writer = new BufferedWriter(new FileWriter(new File(path)));
writer.write(someStuff);
writer.write("\n");
writer.close();
You should probably be following the advice in the answer to the second link you posted. You can access the middle of a file using a random access file, but if you start appending at an arbitrary position in the middle of a file without recording what's there when you start writing, you'll be overwriting its current contents, as noted in this answer. Your best bet, unless the files in question are intractably large, is to assemble a new file using the existing file and your new data, as others have previously suggested.
AFAIK you cannot do that. I mean, appending a line is possible but not inserting in the middle. That has nothing to do with java or another language...a file is a sequence of written bytes...if you insert something in an arbitrary point that sequence is no longer valid and needs to be re-written.
So basically you have to create a function to do that read-insert-slice-rewrite
I have a program that loads lines from a user file, then selects the last part of the String (which would be an int)
Here's the style it's saved in:
nameOfValue = 0
nameOfValue2 = 0
and so on. I have selected the value for sure - I debugged it by printing. I just can't seem to save it back in.
if(nameOfValue.equals(type)) {
System.out.println(nameOfValue+" equals "+type);
value.replace(value, Integer.toString(Integer.parseInt(value)+1));
}
How would I resave it? I've tried bufferedwriter but it just erases everything in the file.
My suggestion is, save all the contents of the original file (either in memory or in a temporary file; I'll do it in memory) and then write it again, including the modifications. I believe this would work:
public static void replaceSelected(File file, String type) throws IOException {
// we need to store all the lines
List<String> lines = new ArrayList<String>();
// first, read the file and store the changes
BufferedReader in = new BufferedReader(new FileReader(file));
String line = in.readLine();
while (line != null) {
if (line.startsWith(type)) {
String sValue = line.substring(line.indexOf('=')+1).trim();
int nValue = Integer.parseInt(sValue);
line = type + " = " + (nValue+1);
}
lines.add(line);
line = in.readLine();
}
in.close();
// now, write the file again with the changes
PrintWriter out = new PrintWriter(file);
for (String l : lines)
out.println(l);
out.close();
}
And you'd call the method like this, providing the File you want to modify and the name of the value you want to select:
replaceSelected(new File("test.txt"), "nameOfValue2");
I think most convenient way is:
Read text file line by line using BufferedReader
For each line find the int part using regular expression and replace
it with your new value.
Create a new file with the newly created text lines.
Delete source file and rename your new created file.
Please let me know if you need the Java program implemented above algorithm.
Hard to answer without the complete code...
Is value a string ? If so the replace will create a new string but you are not saving this string anywhere. Remember Strings in Java are immutable.
You say you use a BufferedWriter, did you flush and close it ? This is often a cause of values mysteriously disappearing when they should be there. This exactly why Java has a finally keyword.
Also difficult to answer without more details on your problem, what exactly are you trying to acheive ? There may be simpler ways to do this that are already there.