Latest Tutorials| Questions and Answers|Ask Questions?|Site Map



Home Answers Viewqa Java-Beginners Writing and Reading A File
Login         

View Questions and Answers by Category

Advertisements


 
Have Programming Question? Ask it here!
 
 
 


Mike Lee
Writing and Reading A File
2 Answer(s)      2 years and a month ago
Posted in : Java Beginners


Hello, I've been trying to learn writing and reading data from file for our assignment, but just stuck on how to proceed. Our assignment requires us to make an application to read and write customer contact information the user enters. Our assignment requires us to make GUI apps. I decided to make a JTable with 3 columns and 3 rows just for simplicity (FirstName, LastName, Age). I also made an empty file I named "contactsFile.txt" where I want java to store the customer information permanently. But I am so confused with the concept. I tried some sites for research but were not helping. Please help. Thanks in advance. Below is example of my code.

import java.awt.BorderLayout; import javax.swing.JFrame; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.table.DefaultTableModel; import javax.swing.table.TableColumn; import java.io.FileReader; import java.io.BufferedReader; import java.util.Scanner;

public class ContactInfoProgram extends JFrame {

public static void main (String[] args)  {
       //declare member components
JFrame frame = new JFrame ("Contacts");    
String [] colNames = {"First Name", "Last Name", "Age"};
Object [][] data = new Object[30][5];
DefaultTableModel model = new DefaultTableModel(data, colNames);
JTable contactsTable = new JTable(model);

contactsTable.setAutoResizeMode(JTable.AUTORESIZEOFF); final int columnMI = 1; TableColumn colMI = contactsTable.getColumnModel().getColumn(columnMI); int columnMIwidth = 5;
colMI.setPreferredWidth(columnMIwidth);

 // Set age column to 5 pixels wide
final int columnAge = 3;
TableColumn colAge = contactsTable.getColumnModel().getColumn(columnAge);
int columnAgeWidth = 5;     
colAge.setPreferredWidth(columnAgeWidth);

JScrollPane s = new JScrollPane(contactsTable);

frame.setVisible(true);
frame.setSize(600, 300);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(contactsTable.getTableHeader(), BorderLayout.PAGE_START);
frame.add(contactsTable);

//get data entered by user in the columns and rows. need to tell java where to write
//will need the name of the file. this is contactsFile.txt
//First Name is in index position [0][0]?

} }


Advertisement
View Answers

October 4, 2012 at 5:17 PM


Here is an example of java swing that accepts the user input from the user through GUI components and store the data into the text file.

import java.io.*;
import java.util.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.sql.*;
class Form extends JFrame{

JButton ADD,RETRIEVE;
JPanel panel,pan;
JLabel label1,label2,label3,label4,label5;
final JTextField text1,text2,text3,text4,text5;
Form() {
label1 = new JLabel();
label1.setText("Employee Id:");
text1 = new JTextField(20);

label2 = new JLabel();
label2.setText("Employee Name:");
text2 = new JTextField(20);

label3 = new JLabel();
label3.setText("Employee Designation:");
text3 = new JTextField(20);

label4 = new JLabel();
label4.setText("Employee Salary:");
text4 = new JTextField(20);

label5 = new JLabel();
label5.setText("Employee Address:");
text5 = new JTextField(20);

ADD=new JButton("ADD");
RETRIEVE=new JButton("RETRIEVE");

panel=new JPanel(new GridLayout(6,2));
panel.add(label1);
panel.add(text1);
panel.add(label2);
panel.add(text2);
panel.add(label3);
panel.add(text3);
panel.add(label4);
panel.add(text4);
panel.add(label5);
panel.add(text5);
panel.add(ADD);
panel.add(RETRIEVE);
add(panel,BorderLayout.CENTER);
setTitle("FORM");

ADD.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae){
String id[]={text1.getText()};
String name[]={text2.getText()};
String des[]={text3.getText()};
String sal[]={text4.getText()};
String add[]={text5.getText()};

java.util.List<String> list = new ArrayList<String>();
for(int i = 0; i < id.length; i++) {
String line = id[i]+" "+name[i]+" "+des[i]+" "+sal[i]+" "+add[i];
list.add(line);
}
writeToFile(list, "Employee.txt");
}
});
RETRIEVE.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae){
File file=new File("Employee.txt");
FileInputStream fis = null;
BufferedInputStream bis = null;
DataInputStream dis = null;
String data="";
try {
fis = new FileInputStream(file);
bis = new BufferedInputStream(fis);
dis = new DataInputStream(bis);
while (dis.available() != 0) {
data+=dis.readLine()+"\n";
}
System.out.println(data);
JTextArea area =new JTextArea(10,25);
JScrollPane sPane = new JScrollPane(area);
area.setText(data);
pan=new JPanel();
pan.add(sPane);
JFrame frame=new JFrame();
frame.add(pan);
frame.setSize(300,100);
frame.setVisible(true);

fis.close();
bis.close();
dis.close();
}
catch(Exception e){}
}
});
}
private static void writeToFile(java.util.List<String> list, String path) {
BufferedWriter out = null;
try {
File file = new File(path);
out = new BufferedWriter(new FileWriter(file,true));
for (String s : list) {
out.write(s);
out.newLine();
}
out.close();
} catch(IOException e) {}
}
}
class InsertToFile{
public static void main(String arg[]) {
try
{
Form frame=new Form();
frame.setSize(300,300);
frame.setVisible(true);
}
catch(Exception e)
{}
}
}


October 4, 2012 at 5:20 PM




Related Tutorials/Questions & Answers:
Writing and Reading A File
Writing and Reading A File  Hello, I've been trying to learn writing and reading data from file for our assignment, but just stuck on how to proceed... (FirstName, LastName, Age). I also made an empty file I named "contactsFile.txt" where
Writing to and reading from a binary file in java.
Writing to and reading from a binary file in java.  I have written the following code to convert an ASCII text file to a binary file: public static... work, but the records obtained after reading the binary file are much less than
Advertisements
reading multiple files from a directory and writing them into a single file
reading multiple files from a directory and writing them into a single file... file i get an empty text file can you guide me how to do... static void main(String[]args) throws IOException{ File Folder = new
Writing a Program to calculate Circumference of planets reading from a file and writing to new file.
Writing a Program to calculate Circumference of planets reading from a file and writing to new file.  Hello, I would like to know how to write... stumped when it comes to reading the file and writing to a new file. My code
Writing a Program to calculate Circumference of planets reading from a file and writing to new file.
Writing a Program to calculate Circumference of planets reading from a file and writing to new file.  Hello, I would like to know how to write... it comes to reading the file and writing to a new file. My code is as follows
Reading and Writing files - Java Beginners
Reading and Writing files  Hello, please help me to Develop a simple... from a file. After welcoming the users, ask them for their name and save it to the file. Use the ClassLoader and Properties classes to load the file. You will need
Writing for the Purpose of Reading
Writing for the Purpose of Reading   ... disoriented. - The advantage of web writing is that a greater number of lists... and terms or background reading or reference information. - The font size that you
Reading a text file in java
in java.io.* package for reading and writing to a file in Java. To learn more about reading text file in Java see the tutorial Read File in Java. Thanks...Reading a text file in java  What is the code for Reading a text file
svg file reading and display
svg file reading and display  i want a sample program for reading and displaying the content of a svg file
Thread for reading txt file
Thread for reading txt file  how to use 3 thread to read 3 txt file? To create three threads for reading the file and three threads for getting the strings out of the queue and printing them. thanks
Reading big file in Java
Reading big file in Java  How to read a big text file in Java program?   Hi, Read the complete tutorial at How to read big file line by line in java? Thanks
Reading an excel file into array
Reading an excel file into array  Hi, I'm trying to read in an excel file, search a column for containing key words (entered by a user) and then displaying the matching rows in a table. I'm fairly new to JavaScript. Can anyone
Problem reading word file
Problem reading word file  Deepak you provide me code for extarcting equation from a word file and also to write in a word file.But when I again want to read preveously created word file(created by your code) it gives an error
Reading a big file effeciently
Reading a big file effeciently  How to read a large text file quickly without memory error in Java? What is the best method to read a big file very efficiently? Thanks   Hi, Kindly check the program Java Read File
Reading file into bytearrayoutputstream
input stream and byte output stream. This is and good example of reading file... we have used the class InputStream for reading the file content into byte...*; /** * Example of Reading file into byte array and then write byte array into a file
External file reading in jsp
External file reading in jsp  i have written a jsp page(ReadExt.jsp) in my application which reads a text file content from a system... file. It uses BufferedReader class to read that particular file. <%@ page
External file reading in jsp
External file reading in jsp  i have written a jsp page(ReadExt.jsp) in my application which reads a text file content from a system...; The given code reads the given file. It uses BufferedReader class to read
Best way to reading file in java
Best way to reading file in java  Hi, As a beginner I want to learn about Java programming and make a program for reading a text file in java. What is the best way for reading file in Java? Thanks
file reading - Swing AWT
file reading  hi everybody, i want to know how to read contents of doc or exe file except for txt file in java.   Hi Friend, Use Jakarta POI library to read the contets of doc file: Here is the code: import
Reading .doc file using swing
Reading .doc file using swing  Sir, Could U Please Tell me the Way To Read .doc file in java using swing,with code
File saving and Writing
File saving and Writing   Hello Rose india..... I have a doubt... a "file create option" it will be ".csv" file and i want to write the data from arraylist into .csv file and i want to save that file so it will ask for "save
Reading a xml file - JSP-Servlet
Reading a xml file  Thanks for ur answer sir but problem is that i have to do a reading a xml file of a employee record and then i have to use a employee details to send mail to those employees how to do i sir please help me
Reading and querying an Excel file in JavaScript
Reading and querying an Excel file in JavaScript  Hi, I'm trying to read in an excel file, search a column for containing key words (entered by a user) and then displaying the matching rows in a table. I'm fairly new
Reading a xml file - JSP-Servlet
Reading a xml file  how to read a xml file using jsp and then i have to retrive a data from that file use it in code?  Hi Friend, Please visit the following link: http://www.roseindia.net/jsp/parsing-xml.shtml
problem while reading .csv file
problem while reading .csv file  I have a problem here..... i am reading a .csv extention file which has some value....but the problem is der is an amount column which contains , in between (eg) 3,899.00 which inturns creates
Reading Text file and storing in map
Reading Text file and storing in map  Hi I have multiple text files. I want to read thoses files and store those records in map. Map will be of "LinkedHashMap<String, Map<String, String>>" type. Please let me know
Reading a file from Jar JAVA
Reading a file from Jar JAVA  I have added one excel sheet into a jar file. can anybody tell me how i can read that file. actually when i am running code from eclipse i able to read it but when i am adding that jar file
Reading a file from Jar JAVA
Reading a file from Jar JAVA  I have added one excel sheet into a jar file. can anybody tell me how i can read that file. actually when i am running code from eclipse i able to read it but when i am adding that jar file
Reading string from file timed
Reading string from file timed  So I want to make a file reader/ buffered reader that reads a new line of the textfile, lets say every 30 second. Like it reads the first line, waiting 30 seconds, read the next line and so one
writing and appending to a file
writing and appending to a file  My input file includes data from... and values and writes into an existing file for 'male'. How can I do the same..." + " :class :" + Name);// appends the string to the file
reading dropdown values from properties file in jsp
reading dropdown values from properties file in jsp  reading dropdown values from properties file in jsp
Advertisements
 

 

 

DMCA.com