BufferedWriter write string line by line - java

Hello I am building a program that writes an output to a text file.
In my program my String looks like this:
MyName
Addres
Location
Paycheck
But when I write it to a text file it looks like this:
MyName Addres Location Paycheck
I am writing everything from a single toString method. How can I use bufferedwriter so that it formats the string while writing it?
Here's my code:
if (file != null) {
FileWriter fileWriter = null;
try {
fileWriter = new FileWriter(file.getAbsolutePath());
} catch (IOException e) {
e.printStackTrace();
}
BufferedWriter out = new BufferedWriter(fileWriter);
try {
out.write(emp.toString());
out.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
EDIT:
Here is the toString method for the emp class:
#Override
public String toString() {
return "Name: " + name + " \nDOB: " + dob + " \nAddress: " + address + " \n******Paycheck******\nSalary: "
+ myPaycheck.getSalary() + "\nFederal Income: " + myPaycheck.getTaxes() + "\nSocial Security: "+ myPaycheck.getSocialSecurity() + "\nMedicare: " + myPaycheck.getMedicare()
+ "\nNet Salary: " + myPaycheck.getNetPay() + "";
}

bufferedwriter API
You can use "newLine" easily .
bw.newLine();

You either need to use System.lineSeparator() while writing text to file or change your toString() method to add a line separator between each line or object added
Edit
Your code writes your string as separate line only. Try reading the lines from output file and print each line, you will see that the reader treats each detail as separate line. Now if you wish to write it into the file with exact format so that it is shown in next line in file u have to give the inputs separately maybe by adding the objects to an ArrayList and iterating the same.

Related

Can't replace string in a text file

Following this thread:
I have a text file storing usernames password and bestscore for that user.
Trying to make a simple quiz game. I have a signup panel and when user signs up I store the data in this file and make his best score 0 for the new user.
The text file format for every single line is
{username} {password} {bestScore}
And when the user makes more than his bestScore i try to replace the actual score in the text file with the bestScore.
Well, back to that thread. I did everything line #meriton posted but the text file still hadn't changed. Here is my code:
if (gameData.getBestScore() < gameData.getScore()) {
int oldBestScore = gameData.getBestScore();
String oldLine = gameData.getCurrentUser() + " " + gameData.getCurrentUserPassword() + " " + oldBestScore;
gameData.setBestScore(gameData.getScore());
String newLine = gameData.getCurrentUser() + " " + gameData.getCurrentUserPassword() + " " + gameData.getBestScore();
// TODO replace the points in the text file
//first method
/*try(BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(new File("C:\\Users\\Niki\\Desktop\\Java Projects\\QuizGame\\QuizGame\\usernames.txt"))))) {
String line = br.readLine();
while (line != null) {
if (line.contains(gameData.getCurrentUser())) {
String newLine = gameData.getCurrentUser() + " " + gameData.getCurrentUserPassword() + " " + gameData.getBestScore();
line = line.replace(line, newLine);
break;
}
line = br.readLine();
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}*/
//second method
Path path = Paths.get("C:\\Users\\Niki\\Desktop\\Java Projects\\QuizGame\\QuizGame\\usernames.txt");
Charset charset = StandardCharsets.UTF_8;
String content = null;
try {
content = new String(Files.readAllBytes(path), charset);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(content);
content = content.replaceAll(oldLine, newLine);
System.out.println(content);
gameOverPanel.gameOverLabel.setText("<html><h1>You didn't answer correctly!</h1><hr><h2>The correct answer is: " + gameData.getCurrentQuestion().getCorrectAnswer().getText() + "</h2><h3>Congratulations! New High Score: " + gameData.getBestScore() + "</h3></html>");
}
else {
gameOverPanel.gameOverLabel.setText("<html><h1>You didn't answer correctly!</h1><hr><h2>The correct answer is: " + gameData.getCurrentQuestion().getCorrectAnswer().getText() + "</h2><h3>Your score: " + gameData.getBestScore() + "</h3></html>");
}
}
As you can see I println before editing the content and after that to the console and everything is ok there. The old content is replaced with the new one but the file is not updated with the new content.
Also i tried to do it my way you can see the commented section in my code under the //first method comment. That way still didn't work.
Here:
System.out.println(content);
content = content.replaceAll(oldLine, newLine);
System.out.println(content);
That updates your String variable in memory. That's all this does. But there is no "magic" connection between that value in your memory and the file on disc. That string variable does neither know nor care that you read its content from a file initially.
If you want to update the file content; then you have to write back the changed string into your file. See here for ideas how to do that.
Try to write the content of the variable into the source file.
Files.write(path, content.getBytes(), StandardOpenOption.CREATE);
You have just loaded the content of file in memory and applied the replaceAll on the content variable.
But you must save change into source file.

Java: BufferdWriter prints String into two lines for no reason?

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.

Reading all text files(data set) from one folder in java

Respected Members,
The topic has been discussed previously but the I have tried those. I am facing an issue in reading all text files from one folder. I am calculating the probability for each text file. Each text file has round about 1500 lines.The code I have shown is reading files from folder but it does not execute method for it.I have used two loops in code chunk. I tried to run execution with a value in "i " variable" in both loops. The while loops is executed before FOR loop(showing wrong logic) . I want it to execute "get.probability()" method for each text file. Kindly please look for the issue. It is only running the first file from folder named "cs.txt",calculates it's probability and detects its language
String target_dir = "./testdataset";
int i = 0;
BufferedReader inputStream = null;
File dir = new File(target_dir);
File[] files = dir.listFiles();
for (File f : files) {
if(f.isFile()) {
System.out.println("File name in directory is: " + f);
inputStream = new BufferedReader(new FileReader(f));
//System.out.println("i in FOR loop" + " " + i);
}
String line;
try {
while((line = inputStream.readLine()) != null) {
//System.out.println("i in while loop" + " " + i); just for checking
detector.append(inputStream);
}
//i++;
String lang = detector.detect();
ArrayList<Language> langlist = detector.getProbabilities();
System.out.println("Language Detected for input file is" + " " + lang);
System.out.println("Probability of language is: " + " " + langlist);
inputStream.close();
}
catch(Exception e) {}
}
I think your problem might due to the execution of the try block even though f might be a directory. You can use the continue (see this) keyword to skip to the next iteration of the loop if f is not a file.
I know nothing about the detector, but make sure that input is cleared after inputStream.close() is called, otherwise you might append multiple files to a single detector.
for (File f : files) {
//This will skip the file if it is a directory
if (!f.isFile())
continue;
System.out.println("File name in directory is: " + f);
inputStream = new BufferedReader(new FileReader(f));
String line;
try {
while((line = inputStream.readLine()) != null) {
//System.out.println("i in while loop" + " " + i); just for checking
detector.append(inputStream);
}
//i++;
String lang = detector.detect();
ArrayList<Language> langlist = detector.getProbabilities();
System.out.println("Language Detected for input file is" + " " + lang);
System.out.println("Probability of language is: " + " " + langlist);
inputStream.close();
}
catch(Exception e) {}
}
for reading file just use :
import org.testng.reporters.Files;
String data =Files.readFile(file);
the code will be cleaner and you can do what ever you want

Appending to text file then displaying only certain fields

I'm making a savings calculator using netbeans with a JFrameForm. below is my working code to save to a .txt. for some reason when I click save it will not append to a new line and wont save at all. I would like to then load certain rows to an array and display in my text area. eg the savings field. First code for the save button, second block for the load button.
BufferedWriter writer = null;
try{
writer = new BufferedWriter(new FileWriter("C:\\test.txt"));
writer.write("\n" + date + "\t" + gross + "\t" + tax + "\t" + savings);
}
catch (Exception e){
JOptionPane.showMessageDialog(null, "Error saving");
}finally{
try{
//close the writer
writer.close();
}catch (Exception e){
JOptionPane.showMessageDialog(null, "Error closing save");
}
}
try{
FileReader reader = new FileReader("C:\\test.txt");
BufferedReader br = new BufferedReader(reader);
txaMain.read(br, null);
br.close();
}
catch(Exception E){
JOptionPane.showMessageDialog(null, "Error opening file");
}
for some reason when I click save it will not append to a new line and wont save at all
It is not saving because you are not flushing the character buffer stream that was grab from your write method.
solution:
flush it after you write from the text file
writer = new BufferedWriter(new FileWriter("C:\\test.txt"));
writer.write("\n" + date + "\t" + gross + "\t" + tax + "\t" + savings);
writer.flush();
Also if you want to append to the file while saving the text then add one more parameter in your FileWriter FileWriter("C:\\test.txt, true") true means to append the file when writing.
public FileWriter(String fileName,
boolean append)

Get data from rdf file [duplicate]

This question already has an answer here:
Closed 10 years ago.
Possible Duplicate:
Java - Using Jena APi - Get data from RDF file
I'm using Java and Jena API.
I have the class Person with the datatype properties hasFirstName, hasLastName, hasDateOfBirth, hasGender.
Here is how one person is represented in my RDF file.
<rdf:Description rdf:about="http://www.fam.com/FAM#Bruno04/02/1980 ">
<j.0:FAMhasGender>H</j.0:FAMhasGender>
<j.0:FAMhasDateOfBirth>04/02/1980</j.0:FAMhasDateOfBirth>
<j.0:FAMhasLastName>DS </j.0:FAMhasLastName>
<j.0:FAMhasFirstName> Bruno</j.0:FAMhasFirstName>
</rdf:Description>
I'd like to get for each person the firstname, gender, date of birth and write that information in a text file. The problem I have is that it only writes the first woman/man he finds in the rdf file, but there is more than one woman and man.
Can you please explain me how can I solve this?
Thank you very much.
ExtendedIterator instances = onto.person.listInstances();
Individual instance = null;
Individual firstInstance = null;
while (instances.hasNext()) {
instance = (Individual) instances.next();
gen = instance.getPropertyValue(onto.hasGender).toString();
fname = instance.getPropertyValue(onto.hasFirstName).toString();
dd = instance.getPropertyValue(onto.hasDateOfBirth).toString();
writeFile(fname, dd, genr);}
// Write text file
public void writeFile(String fn, String dbir, String gn) {
String fileout = "D:/file1.txt";
String firstName = fn;
String dateB = dbir;
String gender = gn;
BufferedWriter out;
try {
out = new BufferedWriter(new FileWriter(fileout, true));
if (gender.equals("F")) {
out.write("[label= \"" + firstName + " \"\n\n\"D.Naiss:" + dnai1 + "\", " + shape + "]");
} else if (gender.equals("M")) {
out.write("[label= \"" + firstName + " \"\n\n\"D.Naiss:" + dnai1 + "\", " + shape2 + "]");
}
out.newLine();
// flushes and closes the stream
out.close();
} catch (IOException e) {
System.out.println("There was a problem:" + e);
}
}
Your problem has nothing to do with Jena or RDF but is rather a logic error in your coding.
You call writeFile() inside your while loop which opens a new file, writes the current entry and closes the file. So you are repeatedly overwriting your file with a single entry at one time so you will only ever end up with a single person in the file.
You need to refactor the code to open the file once before the while loop, have the writeFile() method simply add to that file (and not close it) and then close the file after the while loop.
Also as #Udo Kilmaschewski pointed out in your apparent duplicate the genr variable is not defined in the code you showed so you don't appear to be correctly passing the gender from your while loop to the writeFile() function.

Categories