I am trying to use a text file as a database and I came across a problem. The problem is when I write the user info on the text file, it doesn't write to the next line when I add a second user. It just overwrites the old one. How can I add a writeToNextLine kind of thing?
public void addAdmin(String adminName, String adminSurName, String adminUserName, String adminPassword) throws IOException {
BufferedWriter writer = new BufferedWriter(new FileWriter("C:\\Users\\cemon\\IdeaProjects\\Library\\src\\database\\AdminUserData.txt"));
writer.write(adminName + " " + adminSurName);
writer.newLine();
writer.write(adminUserName + " " + adminPassword);
writer.newLine();
writer.close();
}
Bad idea. How do you know you're not adding a duplicate user?
If you want a simple text file as a database, load the text file into memory on startup, e.g. as a Map<String, User> keyed by adminUserName, and add a new user there. Whenever a value changes, write all the users back to the text file.
That also ensures that (future) operations like "remove user" will work correctly.
Recommend implementing a UserStore class with the suggested Map as a field, to keep the implementation hidden (encapsulated) from the rest of your program.
You want to enable append mode in the FileWriter. This means that when you write a new line, instead of overwriting, it adds another line.
Your code should be:
public void addAdmin(String adminName, String adminSurName, String adminUserName, String adminPassword) throws IOException {
BufferedWriter writer = new BufferedWriter(new FileWriter("C:\\Users\\cemon\\IdeaProjects\\Library\\src\\database\\AdminUserData.txt", true));
writer.write(adminName + " " + adminSurName);
writer.newLine();
writer.write(adminUserName + " " + adminPassword);
writer.newLine();
writer.close();
}
Related
I am writing an application that writes to a text file.
In this text file, at the beginning of each line, is the line number
How do I get the current line number so that I can write it in my file?
I've thought of a simple counter, but when I terminate and restart my project the counter would reset back to 1.
I've tried LineNumberReader, but that keeps on giving me 0.
Is there any way to get the current line number when writing to a file?
Thanks
try {
FileWriter writer = new FileWriter("src\\book_store\\transaction.txt", true);
read = new FileReader("src\\book_store\\transaction.txt");
line = new LineNumberReader(read);
for(int i = 0; i < output.size(); i++) {
line.readLine();
temp = line.getLineNumber() + " " + timeStamp2 + " " + output.get(i) + " " + timeStamp + "\n";
output.set(i, temp);
writer.write(output.get(i));
}
writer.close();
read.close();
line.close();
} catch (IOException ex) {
System.out.println("File not found.");
}
The mistake you are making is that while you are writing to a file through FileWriter, you are trying to read the same file using FileReader.
This could potentially work if you fsynced the file after each line. However, this is not what you really want to do. As you see from the comments, people get confused as you are complicating the problem.
You already have the counter. It’s the i loop variable. You might add +1, if you want to start from 1.
try {
OutputStreamWriter writer = new OutputStreamWriter(
new FileOutputStream("x.txt", true), "UTF-8");
BufferedWriter fbw = new BufferedWriter(writer);
fbw.write(newemails + ":" + passwordEntered);
fbw.newLine();
fbw.close();
System.out.println("Poo");
}catch (Exception e) {
System.out.println("Error: " + e.getMessage());
}
I am developing a program which creates accounts on a website and saves the details of these accounts into a text file. Then, another application reads this text file and extracts the account details. It is important for the application to not login in using the same account details. Therefore, I would like to make a program which deletes a couple of lines in the text file and then saves it, so that the application can log in using different account details. Above is the code I have for writing the email and the password to a text file.
I am getting nothing out in my console from my System.out.println() in the following code:
LinkedList<Element> ls = count(list);
File outFile = new File(args[1]);
FileWriter fw = new FileWriter(outFile);
BufferedWriter bw = new BufferedWriter(fw);
for(int i = 0; i < ls.size(); i++) {
bw.write((int) ls.get(i).data);
System.out.println("Written out " + ls.get(i).data);
}
bw.flush();
bw.close();
Element object is only a class with an int key; and an Object data;
The BufferedWriter is writing out to the file as it should, but my Console in Eclipse doesn't get the System.out.println(); calls. When I run it in debug mode with breakpoint at bw.write() I keep pressing F8 (hotkey to resume), until the BufferedWriter is done, but nothing gets into the Console. Any ideas of why?
First, please don't use the System console for your logging. Second, add a call to flush(). Finally, make sure you add the same cast you used before (or just save it to a variable).
int payload = (int) ls.get(i).data;
bw.write(payload);
System.out.println("Written out " + payload);
// Or,
// System.out.println("Written out " + ((int) ls.get(i).data));
System.out.flush();
Try outputting the variables for the for loop such as the ls.size(), if nothing is being output there then your code isn't being called at all but if it is then you should be able to figure out what is wrong.
since we don't know what is in ls we don't know if it may even be empty
so to help us try putting
System.out.println("List: " + ls);
System.out.println("List size: " + ls.size());
just before the for loop and tell us the outputs.
The following code writes an array into the file, but my problem that it writes it on onto one line when instead I needs it to be on a newline every time that it writes and I can't figure out how to make this part of the code work. I tried adding in the code for a newline as you would for strings but I'm assuming this is not the correct way as it doesn't work.
private class SaveButtonListener implements ActionListener
{
public void actionPerformed (ActionEvent event)
{
String [] data = dataSource.getList();
JFileChooser chooser = new JFileChooser();
chooser.setCurrentDirectory(new File("/home/me/Documents"));
int retrival = chooser.showSaveDialog(null);
if (retrival == JFileChooser.APPROVE_OPTION) {
try {
FileWriter fw = new FileWriter(chooser.getSelectedFile()+".txt");
for (int i=0; i<data.length ; i++)
{
fw.write(data[i] + " \n");
}
//fw.write(data.toString());
fw.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
}
Have you tried
fw.write(data[i] + System.getProperty("line.separator"));
Technically it is writing newlines, but it's likely you're viewing the text file with a text editor that doesn't recognize newline by itself (notepad for instance).
Try:
fw.write(data[i] + " \r\n");
You can use a PrintWriter to easily print individual lines
PrintWriter fw = new PrintWriter(new FileWriter(chooser.getSelectedFile()+".txt"));
for (int i=0; i<data.length ; i++) {
fw.println(data[i]);
}
fw.close();
Note, you should put the close in a finally as otherwise there can be situations when close is not called. In fact you should use the new Java 7 try-with-resources synatx:
try(PrintWriter fw = new PrintWriter(new FileWriter(chooser.getSelectedFile()+".txt"))) {
// stuff
} catch (IOException ex) {
ex.printStackTrace();
}
Note that this will output platform specific linebreaks, so \r\n on windows and \n on Unix. One problem that you will run into time and time again when creating files is opening a file created on one platform on another platform.
FileWriter fw = new FileWriter(chooser.getSelectedFile()+".txt");
chooser.getSelectedFile() should already return a file name with extension so trying adding an extension ".txt" to it isn't making much sense to me.
File writing might be a lengthy operation. So you should run the file writing operation inside a separate thread to avoid blocking EDT thread inside which Swing does it's event management and GUI rendering task. Otherwise your application might get FREEZED.
You might be interested with FileWriter(File file, boolean append) to append your data to a existing file.
Try using System.getProperty("line.separator") to get the correct newline separator for your platform.
Alright so this is a general question which probably has an obvious answer. How would I go about having a program that outputs to a data file, and everytime it is rerun I would skip to the next line.
So for example..
If I wanted to write the word "hi" to a data file, and when it rerun there would then be two "hi"'s without the previous one being deleted.
Sorry this is a proof of concept type thing so I dont have any actual code to post with this question.
When you open up a FileOutputStream to the file to write to, use the constructor that takes the File (or String file name) and a boolean append option and set that append option to true. From there, you can wrap whatever stream decorator (PrintWriter for example) around that input stream and you should be good to go.
PrintWriter out = new PrintWriter(new FileOutputStream(fileName, true));
You can do something like this:
try
{
String filename= "file.txt";
FileWriter fw = new FileWriter(filename,true);
fw.write("this is a new line\n");
fw.close();
}
catch(IOException ioe)
{
// Error!
System.err.println("IOException: " + ioe.getMessage());
}