I am a beginner. I have a text file which already has data and the data can be updated but now i would like to add more data from another GUI form to be added at the end of the data
Now it look like this
name//add/password//postcode//email//hpNo//Buyer
I want to add one more item at the end of the row
name//add/password//postcode//email//hpNo//Buyer//PAYMENT
My current code creates a new data instead of adding it to the last column:
String addcash="";
try
{
File file = new File("MyAccount.txt");
Scanner reader = new Scanner (file);
String line = "", oldtext = "", update = "";
while(reader.hasNextLine())
{
line = reader.nextLine();
String[] text = line.split("//");
accNameTextField.setText(new User().getusername());
if (text[0].equals(accNameTextField.getText())){
String update2 = "//" + addcshComboBox.getSelectedItem();
addcash += accNameTextField.getText() + update2 + System.lineSeparator();
}
else
{
addcash += line + System.lineSeparator();
}
}
reader.close();
FileWriter writer = new FileWriter("MyAccount.txt");
writer.write(addcash);writer.close();
}
catch (IOException ioe)
{
ioe.printStackTrace();
}
}
Here is the explaination:
To tell the FileWriter that you want to append the text and not to override the existing file you need to add a parameter to the FileWriter constructor, here is the code:
FileWriter writer = new FileWriter("MyAccount.txt", true); // Add the "true" parameter!
writer.write(addcash);
writer.close();
need the system to know that there is data over there and skip to the next line so i added [text] on this part of the code
if (text[0].equals(accNameTextField.getText())){
String update2 = "//" + text[1] +"//"+ text[2] +"//"+ text[3] +"//"+ text[4] +"//"+ text[5] +"//"+text[6] +"//"+addcshComboBox.getSelectedItem();
addcash += accNameTextField.getText() + update2 + System.lineSeparator();
Related
I used BufferedReader and FileReader to read a file but everytime I read it, it just displays no name found. Thanks in advance.
BufferedReader ifile = new BufferedReader (new FileReader ("data.txt"));
String N;
while(true)
{
N=ifile.readLine();
if (N == null){
System.out.print("\fNo name found\n");
break;
}
number = Integer.parseInt(ifile.readLine());
house = ifile.readLine();
form = ifile.readLine();
dob = ifile.readLine();
System.out.println("Name: " + N + "\nNumber: " + number + "\nHouse: " + house + "\nForm: " + form + "\nDate of Birth: " + dob);
}
ifile.close();
Answer might have already been given in another topic like: Read all lines with BufferedReader
So it might be a duplicate.
However when you read a file via BufferedReader it is recommended you do it like
FileReader filereader = new FileReader("data.txt");
BufferedReader ifile = new BufferedReader(filereader);
String N;
ArrayList<String> file_contents= new ArrayList<String>();
//List will now contain the whole txt
try {
while((N = input.readLine()) != null) {
file_contents.add(N);
}
ifile.close();
}
catch(IOException e){
e.printStackTrace();
}
And then break the list's contents to get what you want.
Using a try/catch block can avoid the error of not knowing how to handle that the file "data.txt" cannot be read.
Your way of doing it (while(true)) doesn't pass the name in any variable so it can be printed out and also just checks if the 1st line of your data.txt file is empty or not and does nothing with the remaining lines if that condition is true.
In addition to the above check if the source of your problem is in the txt file.
For example if its structure is the way you want it to be.
I am currently writing a "text check" program in Java, but somehow I got stuck whilst creating an unique identifier for every file.
Actually I create an new identifier like this:
String identifier = Base64.encode((dateFormat.format(date) + "#" + uuid.toString() + "#" + name+".sc0").getBytes()).replace("=", "");
Also my program creates a new file and opens a BufferedWriter.
Actually when I now try to append (I tried using BufferedWriter#write, too, but it didn't work either.)
If I write this String into the file now, it looks like this:
BlMjAxNi8wMy8zMSAyMDo0MjowOSMzMThhYjRkNS0yNjFhLTQwNjItODkyOS03NzlkZDIyOWY4Nj
dGVzdC5zYzA
but it should be in only one line like this:
BlMjAxNi8wMy8zMSAyMDo0MjowOSMzMThhYjRkNS0yNjFhLTQwNjItODkyOS03NzlkZDIyOWY4NjdGVzdC5zYzA
At first I thought that it would probably have a problem with me creating a new line after using BufferedWriter#write, so I tried flushing my BufferedWriter before creating a new line. It didn't work either...
PS:
The whole neccessary code:
String name = file.getName().substring(0, ind);
File next = new File(folder.getAbsolutePath(), name+".sc0");
String identifier = Base64.encode((dateFormat.format(date) + "#" + uuid.toString() + "#" + name+".sc0").getBytes()).replace("=", "");
try {
next.delete();
next.createNewFile();
BufferedWriter writer = new BufferedWriter(new FileWriter(next));
logger.info("Adding compiler identifier to file ...");
writer.write("#Script0:"+identifier);
writer.flush();
writer.newLine();
for(String str : lines) {
writer.newLine();
writer.append(str);
}
writer.flush();
writer.close();
} catch (IOException e) {
logger.error("Strange bug ... Did you delete the file? Please try again!");
return;
}
It's the encoder, not the BufferedWriter. Base-64 encoding uses a line length of (I believe) 72 characters.
Came across this code which replaces all the characters of the given value.
File temp = File.createTempFile("newfile", ".txt");
FileWriter fw = new FileWriter(temp);
Reader reader = new FileReader(file);
BufferedReader br = new BufferedReader(reader);
while (br.ready()) {
fw.write(br.readLine().replaceAll("n", "j") + "\n");
}
fw.close();
br.close();
reader.close();
temp.renameTo(file);
}
instead of replacing all 'n's with 'j's isn't there a way to specify the index I want to change only?
You can use replaceFirst (that accepts a regex), using the following pattern:
(?<=.{N-1}).
Where "N" is the index you want to replace.
Of course there are many alternatives, look at the String API to fuel your creative fire.
The line within the while statement as follows:
fw.write(br.readLine().replaceAll("n", "j") + "\n");
This can be expanded to:
String str = br.readLine(); //get text
String replace = str.replaceAll("n", "j"); //replace content
replace = replace + "\n"; //add new line
fw.write(replace); //write to file
For your instance of replacing a certain index, you would want to do something similar:
StringBuilder str = new StringBuilder(br.readLine()); //Read line into StringBuilder
if(str.length() > 3) //Check if string is long enough
str.setChar(4, 'x'); //Replace character in line at index 4 to 'x'
fw.write(str); //write to file
After executing the following piece of code
String content = new String("CONSOLIDATED_UNPAID_code_" + code2 + "_" + countryCode2 + " = " + reason2);
try {
fileOutputStream.write(content.getBytes());
}
catch (IOException e) {
e.printStackTrace();
}
output is as follows:.
CONSOLIDATED_UNPAID_code_64 _KE = Account Dormant-Refer to DrawerCONSOLIDATED_UNPAID_code_65 _KE = Wrong/Missing Account Number (EFT)CONSOLIDATED_UNPAID_code_66 _KE = Wrong/Missing Reference
but i want it like
CONSOLIDATED_UNPAID_code_64 _KE = Account Dormant-Refer to Drawer
CONSOLIDATED_UNPAID_code_65 _KE = Wrong/Missing Account Number (EFT)
Pls suggest
I'd have to see the rest of the code to tell you exactly what you should do, but you can simply use the character "\n" in your string.
You can achieve adding new line to a file in quite a few ways, here is the two approaches:
Add a \n to your String which would cause the remainder of the string to be printed in new line
Use PrintWriter's println method to print each string in new line
Also keep in mind that opening a file with Notepad might not recognize \n hence do not display the remainder of string in new line, try opening the file using Notepadd++
String code2 = "code12";
String countryCode2 = "countryCode2";
String reason2 = " \n I am reason.";
String content = new String("CONSOLIDATED_UNPAID_code_" + code2 + "_" + countryCode2 + " = " + reason2);
try {
fout.write(content.getBytes());
//don't forget to flush the output stream
fout.flush();
} catch (IOException e) {
e.printStackTrace();
}
Use PrintWriter as shown below:
String line1 = "This is line 1.";
String line2 = "This is line 2.";
File f = new File("C:\\test_stackoverflow\\test2.txt");
PrintWriter out = new PrintWriter(f);
out.println(line1);
out.println(line2);
//close the output stream
out.close();
First, use a Writer on top of the output stream to write strings to files. This way, you'll be in control of the output character encoding.
Second, if you want to use your platform's line separator, you may use PrintWriter which has println() methods using the correct newline character or character sequence.
PrintWriter writer = new PrintWriter(
new OutputStreamWriter(fileOutputStream, OUTPUT_ENCODING)
);
...
writer.println(content);
Found solution for this . Appending /n wouldnt solve any issue rather use BufferedWriter. BufferedWriter has a inbuilt newline mwthod to do the same. Thanks
Solution:
try {
File file = new File("Danny.txt");
FileOutputStream fileOutputStream = new FileOutputStream(file);
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(fileOutputStream) );
String content = new String("CONSOLIDATED_UNPAID_description_"+code2+"_"+countryCode2+" = "+description2);
bw.write(content);
bw.newLine();
bw.flush();
check = true;
}
catch (IOException e) {
e.printStackTrace();
}
I know previous questions LIKE this one have been asked, but this question has to do with the specifics of the code that I have written. I am trying to update a single line of code on a file that will be permanently updated even when the program terminates so that the data can be brought up again. The method that I am writing currently looks like this (no compile errors found with eclipse)
public static void editLine(String fileName, String name, int element,
String content) throws IOException {
try {
// Open the file specified in the fileName parameter.
FileInputStream fStream = new FileInputStream(fileName);
BufferedReader br = new BufferedReader(new InputStreamReader(
fStream));
String strLine;
StringBuilder fileContent = new StringBuilder();
// Read line by line.
while ((strLine = br.readLine()) != null) {
String tokens[] = strLine.split(" ");
if (tokens.length > 0) {
if (tokens[0].equals(name)) {
tokens[element] = content;
String newLine = tokens[0] + " " + tokens[1] + " "
+ tokens[2];
fileContent.append(newLine);
fileContent.append("\n");
} else {
fileContent.append(strLine);
fileContent.append("\n");
}
}
/*
* File Content now has updated content to be used to override
* content of the text file
*/
FileWriter fStreamWrite = new FileWriter(fileName);
BufferedWriter out = new BufferedWriter(fStreamWrite);
out.write(fileContent.toString());
out.close();
// Close InputStream.
br.close();
}
} catch (IOException e) {
System.out.println("COULD NOT UPDATE FILE!");
System.exit(0);
}
}
If you could look at the code and let me know what you would suggest, that would be wonderful, because currently I am only getting my catch message.
Okay. First off the bat, StringBuilder fileContent = new StringBuilder(); is bad practice as this file could well be larger than the user's available memory. You should not keep much of the file in memory at all. Do this by reading into a buffer, processing the buffer (adjusting it if necessary), and writing the buffer to a new file. When done, delete the old file and rename the secondary to the old one's name. Hope this helps.