I want to write program that stores information about cars. You input for instance brand and owner name for each car in dialog boxes. In the end, a dialog box with information about all cars should be shown by writing the information to a text file and then reading from it to the dialog box. I create a method getInfo which shows the appropriate boxes correctly.
public static void getInfo() {
boolean done = false;
do {
String brand=JOptionPane.showInputDialog(null, "Brand?");
String name=JOptionPane.showInputDialog(null, "Owner?");
if (brand == null) {
done = true;
} else {
String info ="Car: "+brand+" "+"\nOwner: "+name;
String message = " Do you want to input more cars?";
int buttonClicked = JOptionPane.showConfirmDialog(null, message, "", JOptionPane.YES_NO_OPTION);
done = (buttonClicked == JOptionPane.NO_OPTION);
}
} while (!done);
}
public static void main(String[] args) {
getInfo();
}
I am not sure how to add the information to a text file and how to deal with the loops. To write the information to a text file I tried to change the main method to the following
public static void main(String[] args) throws IOException {
try (PrintWriter outstream = new PrintWriter
(new BufferedWriter
(new FileWriter("cars.txt", true)))) {
getInfo();
outstream.println(info);
}
}
What am I missing and how can I implement the functionality?
You can define a BufferedWriter outside of the loop:
File outputFile = new File("path/to/the/file.txt");
if(!outputFile.exists()){
try {
outputFile.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
BufferedWriter bw = null; //this declares a buffer that writes to some stream.
try{
bw = new BufferedWriter(new FileWriter(outputFile,true)); //here we actually create it, and tell it to write to a file stream, directed at the outputFile file.
}catch(IOException e){
e.printStackTrace(); //this is if the file doesn't exist, which shouldn't happen, but we still need to put this here, because better safe than sorry.
}
And then in your loop: after the
String info ="Car: "+brand+" "+"\nOwner: "+name;
do:
String info ="Car: "+brand+" "+"\nOwner: "+name;
try {
bw.write(info);//write the information to the buffer when there's new info.
bw.newLine();
} catch (IOException e) {
e.printStackTrace();
}
and after exiting the loop, call:
bw.close();
First of all, with every loop you are creating a new instance of info, so you will lose the information from the previous runs.
In your main method you are accessing info, but it should not be known in that scope. What you could do, is to return info from the getInfo() method.
You should then also think about line breaks and so on, but for a first try this should be it.
Try the following:
public static void main() {
boolean done = false;
do {
Info info = getInfo();
storeInfo(info);
done = getDone();
} while (!done);
displayInfo();
}
class Info {
private brand;
private owner;
}
Now you can do single things in each method.
getInfo calls showInputDialog and returns an Info object.
storeInfo stores the Info object to a text file.
getDone calls showInputDialog and returns, if the user wants to quit.
displayInfo opens the text file and shows the info.
The easiest way to implement displayInfo migth be:
void displayInfo() {
// Create a window with TextBox
// Open the text file
// Read the content of the text file and add it to the TextBox
}
Related
I'm trying to create a rudimentary history system for a web browser I'm designing, unfortunately, I can only find ways to either store 1 web address for a history, or not at all, the fileWriter and fileOutputStream seem to limit to one single item per write, which would overwrite the previous if I tried to output one at a time.
I would appreciate it if people could either suggest ways to store an entire list of strings in an external txt doc, bonus points if you can retain an order to them
request for code:
private void loadWebPage(String userInput) {
if (stackTest == true) {
forwardStack.push(urlBox.getText());
stackTest = false;
} else {
backStack.push(urlBox.getText());
}
try {
createHistory(urlBox.getText());
// displays the content of a html link in the web window, as per
// user input
webWindow.setPage(userInput);
// sets the text in the urlbox to the user input so they can check
// at any time what page they are on
urlBox.setText(userInput);
} catch (Exception e) {
// if user enters a bad url then produce error
try {
File file = new File(userInput);
webWindow.setPage(file.toURI().toURL());
} catch (Exception e1) {
System.out.println("Error 001: Bad URL");
}
}
}
private void createHistory(String webAddress) {
JMenuItem button = new JMenuItem(webAddress);
history.add(button);
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent histPress) {
loadWebPage(webAddress);
historyStack.push(webAddress);
try {
FileWriter writer = new FileWriter(histPath, false);
writer.write(historyStack);
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
private void recoverHistory() {
//this will read from the txt doc and create a
//history based on past uses of the browser
}
FileWriter will not store any data construct and will overwrite each value if done using string and forLoop
I hope someone knows the answer
I have made a program that is supposed to create a file, write to it, and then read from it. The problem comes with readFile(), where suddenly hasNext() is undefined for Formatter? I thought that
while (file.hasNext()) {
String a = file.next();
System.out.println(a);
would go as long as there was something in the file, copy it to a and then print a? What am I doing wrong?
import java.util.*;
import java.io.*;
class Oppgave3
{
public static void main(String[] args)
{
Kryptosystem a = new Kryptosystem();
a.createFile();
a.writeFile();
a.openFile();
a.readFile();
a.closeFile();
}
}
class Kryptosystem
{
public Kryptosystem(){}
Scanner keyboard = new Scanner (System.in);
private Formatter file;
private Scanner x;
public void createFile(){
try {
file = new Formatter("kryptFil.txt");
}
catch (Exception e) {
System.out.println("could not create file");
}
}
public void writeFile(){
System.out.println("what do you want to write");
String tekst = keyboard.nextLine();
file.format(tekst);
}
public void openFile() {
try {
x = new Scanner (new File("kryptFil.txt"));
}
catch (Exception e) {
System.out.println("something is wrong with the file");
}
}
public void readFile() {
while (file.hasNext()) {
String a = x.next();
System.out.println(a);
}
}
public void closeFile() {
file.close();
}
}
You state:
where suddenly hasNext() is undefined for Formatter?
Please have a look at the Formatter API as it will show you that this class has no hasNext() method, and your Java compiler is correctly telling you the same thing. Similarly, the Scanner API will show you that it in fact has the method you need.
You're opening the same File in a Scanner, called x, and this is what you want to use to read from the file. So the solution is to call hasNext() on the Scanner variable:
while (x.hasNext()) { // x, not file
String a = x.next();
System.out.println(a);
}
Note I'm not sure why you opened the file a second time and placed it into a Formatter object. Please clarify your motivation for this. I believe that you wish to write to the file with this, but you certainly would not try to use it to read from the File, which is what you're use of hasNext() is trying to do. I think you were just a little confused on which tool to use is all.
All, I am trying to read a file which will be written by multiple threads, I am going to use BufferedReader to read that file in a thread.
The code looks like below.
FileReader reader = new FileReader(file);
BufferedReader br = new BufferedReader(reader);
String detail;
while ((detail =br.readLine()) != null)
{
...
}
Currently It seems works fine. But I have some questions about it.
If the question sound silly. please don't laugh at me . thanks.
Is it possible that the loop never been broken ? because the other threads are writing into the file.So maybe the readLine() may never return null?
Updated
Let's say there are 3 threads(T1,T2,T3).
T1 and T2 are writer.
T3 is reader.
The code runs in below sequence.
1.The current file lines number is 100.
2.T1 write a line to file.(file lines increase to 101)
3.T3 reads the last line of file(101). next read will get null.
4.T2 append a line to file.(file lines increase to 102)
5.T3 read again....(Does it return null or not? because T2 just added a new line into file before T3 read again.)
Please help to review it .thanks in advance.
Yes, it is possible that the loop will never end (at least until you run out of memory). Here's some code to prove it:
public class test {
public static void main(String[] args) {
// start thread to write to file
new Thread(new Runnable() {
#Override
public void run() {
FileWriter writer;
try {
int i = 1;
writer = new FileWriter("D:\\text.txt");
writer.append("line"+ i++ + "\n");
writer.flush();
while (true)
{
writer.append("line"+ i++ + "\n");
writer.flush();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
try {
Thread.sleep(500);
} catch (InterruptedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
// start thread to read file
new Thread(new Runnable() {
#Override
public void run() {
try {
FileReader reader = new FileReader("D:\\text.txt");
BufferedReader br = new BufferedReader(reader);
String detail;
while ((detail =br.readLine()) != null)
{
System.out.println(detail);
}
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
}
}
I did some experiment for it .
One eclipse run a program as writer .
public class Main {
private static Logger log = Logger.getLogger(Main.class);
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
PropertyConfigurator.configure("log4j.properties");
log.warn("Test test test ");
}
}
Another eclipse run the program as reader.
public class Main {
/**
* #param args
* #throws IOException
*/
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
StringBuffer intiLine = new StringBuffer("");
FileReader reader = new FileReader("D:\\logs\\notify-subscription.log");
BufferedReader br = new BufferedReader(reader);
String detail;
while ((detail =br.readLine()) != null)//debug and set breakpoint here
{
System.out.println(detail);
}
}
}
before I began to test them. The original log file content is empty.
I ran the reader program at first. the result of br.readLine() supposed to be null. But I set break point at the code line while ((detail =br.readLine()) != null) run, before it run , I ran the writer program. So the file contains test test test. and br.readLine() will not be null.
You are absolutely Correct .There will be a chance for Deadlock also if you keep creating threads for writing content to the file.Because if threads are keep on writing to the file there wont be any chance of exiting from loop it goes to infinite state
I've an app that is writing data to a file. The first time I run it, it goes grand and writes 1000s of values to the file. Then I close the app using this code
finish();
System.exit(0);
Which happens when I hit the stop button.
When I run it again after stopping, say in a few minutes, it only writes a few values to a new file, over the same time frame.
Here is the code I use to write to the file:
public void write(String message) {
try {
if (out == null) {
FileWriter datawriter = new FileWriter(file, true);
out = new BufferedWriter(datawriter);
//out.write("X Value, Y Value, Z Value \n");
}
if (file.exists()) {
out.append(message);
out.flush();
}
Any insight into why this is happening would be much appreciated.
Thanks
On finishing do out.close(). It probably is a system deteriorating.
Do not call
System.exit(0);
Read this post to know why.
Also, you shouldn't need to call flush(), but just close() when you're done, before your call to finish().
Try with this code:
public void write(String message) {
try {
if (out == null) {
FileWriter datawriter = new FileWriter(file, true);
out = new BufferedWriter(datawriter);
}
out.append(message);
out.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
I'm trying to monitor the file content and adding any new line to JTextArea. I created thread, which monitor the file, but when the Scanner object reachs the end of file it stop working. I tried very simple method, which create new Scanner object and read the file from the begin, but it isn't good solution.
It's the version which stop and do nothing :
public class TextAreaThread implements Runnable {
JTextArea text = null;
File file = null;
Scanner read = null;
public TextAreaThread(JTextArea text, File file) {
this.text = text;
this.file = file;
try{
read = new Scanner(file);
}catch(FileNotFoundException e){
JOptionPane.showMessageDialog(null,"Wrong file or file doesn't exist","Error",JOptionPane.ERROR_MESSAGE);
}
}
public void run() {
while(true){
while(read.hasNext())
text.append(read.nextLine()+"\n");
try {
wait(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
The wait method is not what you want here. Try Thread.sleep instead.