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.
Related
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.
So say for example I have this file
I want my program to search for the title and respective author using the input from the user and then ask for replacement values. Then these replacements will change the current value in the file.
This is my current implementation:
import java.io.*;
import javax.swing.*;
public class SecondChild4 extends SecondParent
{
public void edit(String sFileName, String sFileName2)
{
try
{
sFileName2 = "Second.txt";
File nfile2 = new File("Second.txt");
File file2 = new File("TempSecond.txt");
FileReader reader2 = new FileReader(sFileName2);
BufferedReader br2 = new BufferedReader(reader2);
FileWriter twriter2 = new FileWriter(file2);
BufferedWriter tbw2 = new BufferedWriter(twriter2);
String line2 = "";
String edit2 = "";
String btitle = JOptionPane.showInputDialog (null, "Title: ", "");
String bauthor = JOptionPane.showInputDialog (null, "Author: ", "");
//how to search if value was found from the file?
String btitle1 = JOptionPane.showInputDialog (null, "Replace with title: ", "");
String bauthor1 = JOptionPane.showInputDialog (null, "Replace with author: ", "");
line2 = br2.readLine();
while(line2 != null){
if (line2 == null)
{
// End of File
tbw2.close();
br2.close();
}
else if(what condition to put here?)
{
System.out.println("Search found");
edit = line2.replaceAll(btitle, btitle1);
edit2 = line2.replaceAll(bauthor, bauthor1);
tbw1.append(edit);
tbw1.append(",");
tbw1.append(edit2);
tbw1.append("\n");
tbw2.write(edit);
tbw2.write("\t");
tbw2.write(edit2);
tbw2.newLine();
tbw1.close();
tbw2.close();
br1.close();
br2.close();
}
else{
tbw1.append(line1);
tbw1.append("\n");
tbw2.write(line2);
tbw2.newLine();
tbw1.close();
tbw2.close();
br1.close();
br2.close();
}
}
file2.delete();
file2.renameTo(nfile2);
}
catch(IOException e)
{
e.printStackTrace();
}
}
}
I made a temp file for the storage of the modified values and then delete the old file and rename the temp file according to the previous file's name. In the code I made, there are problems such as the file contents get empty(I am also saving it in csv but did not put the codes related to that here. When it comes to csv, only the first line of the previous file gets rewritten to the temp), the file don't get deleted and renamed.
I know there are lots of mistakes with my code. I'm pretty new to programming. Please help me :)
You can do it nicely by creating a book.properties file like
Title=Foo
Author=bar
Java code will be like :
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
public class SecondChild4 {
private InputStream inputStream;
public static void main(String[] args) {
SecondChild4 s = new SecondChild4();
s.getPropValues();
}
public String getPropValues() {
String result = "";
try {
Properties prop = new Properties();
String propFileName = "book.properties";
inputStream = getClass().getClassLoader().getResourceAsStream(propFileName);
if (inputStream != null) {
prop.load(inputStream);
} else {
throw new FileNotFoundException("property file '" + propFileName + "' not found in the classpath");
}
// get the property value and print it out
String title = prop.getProperty("Title");
String author = prop.getProperty("Author");
result = "Book = " + author + " title " + title;
System.out.println("current book details are " + result);
// replace logic here
prop.setProperty("Title", "Hamlet");
prop.setProperty("Author", "William Shakespeare");
System.out.println("after modification");
result = "Book = " + prop.getProperty("Author") + " title " + prop.getProperty("Title");
System.out.println("cuurrent book details are " + result);
} catch (Exception e) {
System.out.println("Exception: " + e);
} finally {
try {
inputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return result;
}
}
Output :
current book details are Book = bar title Foo after modification
current book details are Book = William Shakespeare title Hamlet
Some things for you to remember while coding :
Dont put everything in try catch block just for sake of avoiding exceptions,keep only part that actually throws that exception...not whole code.
call all close methods eg: buffereader.close() in finally block
Never, never, never throw an exception , instead catch it there itself.
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
Good day! I use such part of code
File file = new File(someFilePath);
Scanner sc;
try {
sc = new Scanner(file);
} catch (FileNotFoundException e) {
return "";
}
sc.useDelimiter("\\Z");
System.out.println("file : " + file.getName() + " " + sc.hasNext() + " " + sc.delimiter());
String fileString = sc.next();
I get error Exception in thread "main" java.util.NoSuchElementException at last line of this piece of code.
And the output is file : 758279215_profile.txt false \Z, so the delimiter is correct, file exists (and it's not empty, I've checked it), but it has no next element for some reason (and as I think next element should be and it should be the whole text in the file). What's wrong and how to fix it? Thank you!
ADDED:
BufferedReader br = new BufferedReader(new FileReader(file));
String line = "";
while (line != null) {
try {
line = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println(line);
}
returns content of a file (text file with content edited as JSON text) and null (the last itteration of the loop)
it could be locale issue.
try export LC_ALL=en_US.utf-8
I am creating an XML file from my Database and storing it in Internal storage. I require data from XML file into a single string. For which, i am using the following method.
BufferedReader br;
try {
br = new BufferedReader(new FileReader(new File(pathDAR)));
String line;
StringBuilder sb = new StringBuilder();
while ((line = br.readLine()) != null) {
sb.append(line.trim());
String temp = sb.toString().substring(38);
Log.v("XML TO String", "" + temp);
Log.v("Lengths : ", "" + temp.length() + " " + sb.length());
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
I have been getting string in the Log, but it seems to be stopping abruptly in the middle.
For e.g. I am supposed to get records string like this. Beginning and ending with database tag.
<database name="DAR.db"><table name="DARWorkDetails"><row><col name="id">1</col><col name="date">05-28-2013</col><col name="visited_city_ID">1264</col><col name="employee_ID">107</col><col name="work_type_ID">1</col><col name="name">null</col><col name="customer_Id">null</col><col name="customer_type_ID">null</col><col name="sub_customer_id">null</col><col name="reason_ID">14</col><col name="reason">ABM SM MEETING</col><col name="remarks">gfhii</col><col name="work_with">211,162</col><col name="IsCustomer">N</col><col name="created_by">107</col><col name="position_id">72</col><col name="designation_Id">3</col><col name="submit_date">05-28-2013</col><col name="IsFinal">null</col></row></table></database>
Instead i have been getting string like this :
<database name="DAR.db"><table name="DARWorkDetails"><row><col name="id">1</col><col name="date">05-28-2013</col><col name="visited_city_ID">1264</col><col name="employee_ID">107</col><col name="work_type_ID">1</col><col name="name">null</col><col name="customer_Id">null</col><col name="customer_type_ID">null</col><col name="sub_customer_id">null</col><col name="reason_ID">14</col><col name="reason">ABM SM MEETING</col><col name="remarks">gfhii</col><col name="work_with">211,162</col><col name="IsCustomer">N</col><col name="created_by">107</col><col name="position_id">72</col><col name="designation_Id">3</col><col name="submit_date">05-28-2013</col><col name="IsFinal">null</co
The String is stopping in the middle. For the sake of example i have only put small example string above. In reality my database has multiple records and i have counted length of the string to around 15640, before abrupt end of the string.
Are there any limitations with StringBuilder in regards to storing characters? I suppose there is memory issue since i have been able to get string fully for records fewer than 10. Problem seems to be arising when records go into upwards of 10. Any help in understanding of solving this issue would be much appreciated.
Please check
It may happen your output is perfect but your Log cat is not displaying it whole.
Log.v("XML TO String", "" + temp);
Log.v("Lengths : ", "" + temp.length() + " " + sb.length());
See reference
I created this class to read strings from a xml file saved in internal storage device, it returns a list , if you want the whole extended string you only need concatenate to link together, if doesn't found the file return an empty list this is all you need to read XML files and parse to Strings, I hope to help!
public class readXMLFile {
private String filePath = "FileStorage";
private String fileName = "File.xml";
private final String tag = "Internal Read Persistence";
File internalFileData;
public readXMLFile() {// default constructor
}
public File getXMLFile(Context context){
File directory = null;
ContextWrapper cw = new ContextWrapper(context);
directory = cw.getDir(filePath, Context.MODE_PRIVATE);
internalFileData = new File(directory, fileName);
if(internalFileData.exists()){
Log.i("ReadXMLFile","File returned");
return internalFileData;
}
else{
Log.i(tag,"the file doesn't exists!");
return null;
}
}
public List<String> readFile(Context context) {
List<String> l = new LinkedList<String>();
try {
File directory = null;
ContextWrapper cw = new ContextWrapper(context);
directory = cw.getDir(filePath, Context.MODE_PRIVATE);
internalFileData = new File(directory, fileName);
if (internalFileData.exists()) {
Log.i("Internal Data", "the root exists!!");
try {
FileInputStream fis = new FileInputStream(internalFileData);
DataInputStream in = new DataInputStream(fis);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String line;
while ((line = br.readLine()) != null) {
l.add(line);
}
try {
if (in != null) {
in.close();
}
} catch (Exception e) {
Log.i(tag, "Exception closing persistence connection");
}
} catch (Exception e) {
Log.wtf("Fatal Exception", "Exception: " + e.getMessage());
}
} else {
Log.i(tag, "File doesn't exists");
return l;//return empty list
}
} catch (Exception e) {
Log.wtf(tag, "Exception DATA READING: " + e.getMessage());
return l;
}
Log.i(tag, "file found return");
return l;
}
}