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. 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]?
}
}
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 FileWriting 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 and Writing files - Java BeginnersReading 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
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 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
Thread for reading txt fileThread 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 JavaReading 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
Problem reading word fileProblem
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 an excel file into arrayReading 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
Reading a big file effecientlyReading 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...
In this example we have used the class InputStream
for
reading the
file...
import java.io.*;
/**
* Example of
Reading file into byte array
External file reading in jspExternal
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 jspExternal
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 javaBest 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 AWTfile 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
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-ServletReading 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
writing and appending to a filewriting 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 problem while reading .csv fileproblem 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 a xml file - JSP-ServletReading 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
Reading and querying an Excel file in JavaScriptReading 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 Text file and storing in mapReading 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
File Writing - Java BeginnersFile Writing Hi... I need a syntax or logic or program by which we can write into the desired shell of the Excel
file from console window... Hi friend,
I am sending you a link. This is will help you. Please
Reading a file from Jar JAVAReading 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 JAVAReading 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 timedReading 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
xml file reading using javaxml
file reading using java hi deepak
I want to read some data from xml
file and send that output to particular email address using java
import org.w3c.dom.*;
import org.w3c.dom.Node;
import javax.xml.parsers.
Reading And Writing Excel File
reading and
writing excel
file
...
org.apache.poi.poif.filesystem.POIFileSystem class is used to buffer
the excel
file into an object. In other words, we can say that it is used to read
the excel
file. After
reading the excel
Writing xml file - Java BeginnersWriting xml file Thank you for the quick response
The values which... XmlServlet().createXmlTree(doc);
System.out.println("Xml
File Created... = sw.toString();
File file = new
File("c:/newxml.xml
initialise array by reading from file - Java Beginnersinitialise array by
reading from file Hello, I wnat to know how i would initialise an array by
reading a text
file, which contains a simple pattern.
for example the
file may look as shown below, with the star character
Writing a file using servlets - JSP-Servlet reading the data and creating a
file in my space. but it is not
writing...
Writing a
file using servlets I'm using a servlet to read an input..., but its not
writing in the xyz.txt
file. I think
writing in a servlet should
Java example for Reading file into byte arrayJava example for
Reading file into byte array. You can then process the byte... in Java for
reading file into
byte array. Sometimes it becomes necessary... code example explains the process
of
reading file into byte array
Writing Log Records to a Log File Writing Log Records to a Log
File
This section demonstrates for
writing log records to a
log
file. Logger provides different types of level like: warning, info
Large File reading through Axis2 Web serviceLarge
File reading through Axis2 Web service This is Vinay Rai.
This is regarding the web service help which i am looking for. I am currently working on axis2 web service and i am very new to this. so need your help
reading a file on server side - JSP-Servletreading a
file on server side Thank you sir for replying... &
reading a word
file in JSP which is uploaded by client.
please help me...:
Display
file upload form to the user
UPLOAD THE
FILE
Choose the
file jar file not reading input from serial portjar
file not
reading input from serial port i used a coding for getting data from serial port. JOptionbox with "port not found" message is shown when i execute thru jar
file. but when i execute thru netbeans, data is received
jar file not reading input from serial portjar
file not
reading input from serial port i used a coding for getting data from serial port. JOptionbox with "port not found" message is shown when i execute thru jar
file. but when i execute thru netbeans, data is received
reading data from excel file and plotting graphreading data from excel
file and plotting graph I am doing a project using NetBeans in which i have to take input an excel
file and then using the data in excel
file, i have to plot graphs based on CELL ID selected. please help