| | |
writting and reading a file
Please support our Java advertiser: Programming Forums - DaniWeb Sister Site
Thread Solved |
•
•
Join Date: Apr 2008
Posts: 108
Reputation:
Solved Threads: 1
I have to write two programs, one writes to file based on what the user selects. The other reads the file, and outputs what the user selects. And I'm really not sue if I'm doing this right.
Here is what I have for writting to the file:
Did I do this correctly?
Here is what I have for writting to the file:
Java Syntax (Toggle Plain Text)
import javax.swing.*; import java.awt.*; import java.awt.event.*; import java.io.*; /* * class LogOrder * Allows user to pick from five pieces of clothing to order * user enters name and picks clothing and presses order. * Stores users order to "order.txt" * @author Kimberlie Davis * @version 11/20/08 */ public class LogOrder { /* * main method * declares and sets frame as visible * @param args not used */ public static void main(String args[]) { EventQueue.invokeLater( new Runnable() { public void run() { LogOrderFrame mainFrame = new LogOrderFrame(); mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); mainFrame.setVisible(true); } }); } } /* * LogOrderFrame method * sets up frame * Declares and adds panel */ class LogOrderFrame extends JFrame { public LogOrderFrame() { this.setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT); LogOrderPanel panel = new LogOrderPanel(); this.add(panel); this.setTitle("Log order"); } private static int DEFAULT_WIDTH = 500; private static int DEFAULT_HEIGHT = 500; } /* * LogOrderPanel method * Layouts and panels * Sets up panel with components * adds actionListener to button */ class LogOrderPanel extends JPanel { public LogOrderPanel() { //set up Buffered writer try { writer = new BufferedWriter(new FileWriter("order.txt")); } catch(IOException e) { } //set up layouts this.setLayout(new BorderLayout()); //north JPanel north = new JPanel(new BorderLayout()); this.add(north, BorderLayout.NORTH); //north center JPanel northCenter = new JPanel(); north.add(northCenter, BorderLayout.CENTER); //center JPanel center = new JPanel(); this.add(center, BorderLayout.CENTER); Box boxLayout = Box.createVerticalBox(); center.add(boxLayout); //set up components JLabel companyName = new JLabel("Clothing Inc."); JLabel askName = new JLabel("Please enter your name:"); enterName = new JTextField(5); //Array of 5 checkboxes for(int i = 0; i < 5; i++) { check[i] = new JCheckBox(); } check[0].setText("Jacket"); check[1].setText("Shirt"); check[2].setText("Pants"); check[3].setText("Socks"); check[4].setText("Shoes"); JButton order = new JButton("Order"); //add components northCenter.add(askName); northCenter.add(enterName); boxLayout.add(check[0]); boxLayout.add(check[1]); boxLayout.add(check[2]); boxLayout.add(check[3]); boxLayout.add(check[4]); north.add(companyName, BorderLayout.NORTH); this.add(order, BorderLayout.SOUTH); ClothingChooser chooseAction = new ClothingChooser(); order.addActionListener(chooseAction); } /* * ClothingChooser class * implements ActionListener * sets up actions for button */ private class ClothingChooser implements ActionListener { /* * actionPerformed method * checks what checkboxes have been selected * stores users order to file "order.txt" * @param ActionEvent */ public void actionPerformed(ActionEvent e) { try { try { writer.write("Order:" + '\n'); writer.write("For: " + enterName.getText() + '\n'); if(check[0].isSelected()) writer.write('\t' + "Jacket" + '\n'); if(check[1].isSelected()) writer.write('\t' + "Shirt" + '\n'); if(check[2].isSelected()) writer.write('\t' + "Pants" + '\n'); if(check[3].isSelected()) writer.write('\t' + "Socks" + '\n'); if(check[4].isSelected()) writer.write('\t' + "Shoes" + '\n'); writer.write('\n'); } finally { JOptionPane.showMessageDialog(null, "Conratulations " + enterName.getText() + " your order was successful!"); } } catch(IOException exception) { JOptionPane.showMessageDialog(null, "Error: Order not receive\n Please call Clothing Inc. to order"); } } } //datafields JCheckBox[] check = new JCheckBox[5]; BufferedWriter writer; JTextField enterName; }
Last edited by christiangirl; Nov 20th, 2008 at 2:12 am.
•
•
Join Date: Apr 2008
Posts: 108
Reputation:
Solved Threads: 1
I figured that out, but am still having problems. here is my new code:
The problems I'm having now is inside of the file the text is not formatted how I want it, its supposed to be all on different lines. And also, if the user submits another order the file is supposed to show both, but it is only showing one.
Java Syntax (Toggle Plain Text)
import javax.swing.*; import java.awt.*; import java.awt.event.*; import java.io.*; /* * class LogOrder * Allows user to pick from five pieces of clothing to order * user enters name and picks clothing and presses order. * Stores users order to "order.txt" * @author Kimberlie Davis * @version 11/20/08 */ public class LogOrder { /* * main method * declares and sets frame as visible * @param args not used */ public static void main(String args[]) { EventQueue.invokeLater( new Runnable() { public void run() { LogOrderFrame mainFrame = new LogOrderFrame(); mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); mainFrame.setVisible(true); } }); } } /* * LogOrderFrame method * sets up frame * Declares and adds panel */ class LogOrderFrame extends JFrame { public LogOrderFrame() { this.setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT); LogOrderPanel panel = new LogOrderPanel(); this.add(panel); this.setTitle("Log order"); } private static int DEFAULT_WIDTH = 500; private static int DEFAULT_HEIGHT = 500; } /* * LogOrderPanel method * Layouts and panels * Sets up panel with components * adds actionListener to button */ class LogOrderPanel extends JPanel { public LogOrderPanel() { //Writer writeTo = new File("order.txt"); /*try { //toStream = new FileWriter(writeTo); } catch(IOException e) { }*/ //set up layouts this.setLayout(new BorderLayout()); //north JPanel north = new JPanel(new BorderLayout()); this.add(north, BorderLayout.NORTH); //north center JPanel northCenter = new JPanel(); north.add(northCenter, BorderLayout.CENTER); //center JPanel center = new JPanel(); this.add(center, BorderLayout.CENTER); Box boxLayout = Box.createVerticalBox(); center.add(boxLayout); //set up components JLabel companyName = new JLabel("Clothing Inc."); JLabel askName = new JLabel("Please enter your name:"); enterName = new JTextField(5); //Array of 5 checkboxes for(int i = 0; i < 5; i++) { check[i] = new JCheckBox(); } check[0].setText("Jacket"); check[1].setText("Shirt"); check[2].setText("Pants"); check[3].setText("Socks"); check[4].setText("Shoes"); JButton order = new JButton("Order"); //add components northCenter.add(askName); northCenter.add(enterName); boxLayout.add(check[0]); boxLayout.add(check[1]); boxLayout.add(check[2]); boxLayout.add(check[3]); boxLayout.add(check[4]); north.add(companyName, BorderLayout.NORTH); this.add(order, BorderLayout.SOUTH); ClothingChooser chooseAction = new ClothingChooser(); order.addActionListener(chooseAction); } /* * ClothingChooser class * implements ActionListener * sets up actions for button */ private class ClothingChooser implements ActionListener { /* * actionPerformed method * checks what checkboxes have been selected * stores users order to file "order.txt" * @param ActionEvent */ public void actionPerformed(ActionEvent e) { try { try { toStream = new FileWriter(writeTo); toStream.write("Order:" + '\n'); toStream.write("For: " + enterName.getText() + '\n'); if(check[0].isSelected()) toStream.write('\t' + "Jacket" + '\n'); if(check[1].isSelected()) toStream.write('\t' + "Shirt" + '\n'); if(check[2].isSelected()) toStream.write('\t' + "Pants" + '\n'); if(check[3].isSelected()) toStream.write('\t' + "Socks" + '\n'); if(check[4].isSelected()) toStream.write('\t' + "Shoes" + '\n'); toStream.write('\n'); toStream.close(); } finally { JOptionPane.showMessageDialog(null, "Conratulations " + enterName.getText() + " your order was successful!"); } } catch(IOException exception) { JOptionPane.showMessageDialog(null, "Error: Order not receive\n Please call Clothing Inc. to order"); } } } //datafields JCheckBox[] check = new JCheckBox[5]; File writeTo; JTextField enterName; FileWriter toStream; }
The problems I'm having now is inside of the file the text is not formatted how I want it, its supposed to be all on different lines. And also, if the user submits another order the file is supposed to show both, but it is only showing one.
•
•
Join Date: Aug 2008
Posts: 16
Reputation:
Solved Threads: 1
...
toStream = new FileWriter(writeTo);
toStream.write("Order:" + '\n');
...
The logic from that line is that each time you have a new order coming, it will "create" a new blank page. Maybe you can try to use 'if' to check whether or not your order.txt is empty. If it's not then just add your line(s).
Or easier if you just use your BufferedWriter code instead of that FileWriter code.
As for the line breakdown, if you are using BufferedWriter just add command:
toStream = new FileWriter(writeTo);
toStream.write("Order:" + '\n');
...
The logic from that line is that each time you have a new order coming, it will "create" a new blank page. Maybe you can try to use 'if' to check whether or not your order.txt is empty. If it's not then just add your line(s).
Or easier if you just use your BufferedWriter code instead of that FileWriter code.
As for the line breakdown, if you are using BufferedWriter just add command:
Java Syntax (Toggle Plain Text)
writer.newLine();
Vee Liang
To be right, first you have to know what wrong is.
To be right, first you have to know what wrong is.
In what way?
You do know, it is always helpful if you post exactly what it is that is not happening as expected (along with all compiler/error messages).
You do know, it is always helpful if you post exactly what it is that is not happening as expected (along with all compiler/error messages).
Java Programmer and Sun Systems Administrator
----------------------------------------------
Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it.
--Brian Kernighan
----------------------------------------------
Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it.
--Brian Kernighan
So take a look at liang's answer again. It has nothing to do with the if statement, it has to do with the fact that you are creating a new FileWriter with every "button-click", which will overwrite everything that's been written before it.
If you want to recreate the FileWriter every time then do it in append mode
And, you should be closing the writer in the finally block, and, as your code is now, even if there is an exception, the "success" message will still be shown (that should be in the try block, and the close in the finally block).
If you want to recreate the FileWriter every time then do it in append mode
Java Syntax (Toggle Plain Text)
new FileWriter(file, true);
And, you should be closing the writer in the finally block, and, as your code is now, even if there is an exception, the "success" message will still be shown (that should be in the try block, and the close in the finally block).
Last edited by masijade; Nov 20th, 2008 at 5:01 am.
Java Programmer and Sun Systems Administrator
----------------------------------------------
Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it.
--Brian Kernighan
----------------------------------------------
Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it.
--Brian Kernighan
Java Programmer and Sun Systems Administrator
----------------------------------------------
Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it.
--Brian Kernighan
----------------------------------------------
Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it.
--Brian Kernighan
![]() |
Similar Threads
- QuickTime 7.0.4 won't uninstall (Windows Software)
- Creating a Script Language In C# (C#)
- how to read many text file? (C++)
- help finding line in file! (C++)
- reading ints from a binary file (C)
- Why does my code not take my input? (C++)
- Virus Programming (Assembly)
- String to disk with fstream (C++)
- files in C++ (C++)
Other Threads in the Java Forum
- Previous Thread: Reading from a file
- Next Thread: Play a .wav file
Views: 877 | Replies: 11
| Thread Tools | Search this Thread |
Tag cloud for Java
android api apple applet application arguments array arrays automation bidirectional binary birt bluetooth calculator chat class classes client code columns component database designadrawingapplicationusingjavajslider detection draw eclipse editor error errors event exception expand file fractal game givemetehcodez graphics gui guidancer helpwithhomework html ide image inetaddress input integer intellij j2me java javamicroeditionuseofmotionsensor javaprojects jme jmf jni jpanel julia linux list loop map method methods mobile mobiledevelopmentcreatejar myaggfun netbeans newbie number object oracle os plazmic print problem program programming project recursion scanner screen server set signing size smart sms smsspam socket sort sql string subclass support swing test threads time transfer tree windows






