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




Have Programming Question? Ask it here!
 
 
 


Steve
Text File I/O - DVD.java
0 Answer(s)      4 years and a month ago
Posted in : Java Beginners


NEED HELP PLEASE.

The application should use a text file with one value on each line of the file. Each movie would use three lines: one for title; one for studio; one for year.

When the application starts, read the data file and populate the array. When the file ends, use the array to recreate the file.

Here is my code but I need to modify it to the specifications on top. I don't know where to begin.

Thanks.

//package dvd;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.text.*;
import java.io.*;
import java.util.*;

public class DVD extends JFrame implements ActionListener
{
//Declare output stream
DataOutputStream output;

//construct components
JLabel sortPrompt = new JLabel("Sort by:");
JComboBox fieldCombo = new JComboBox();
JTextPane textPane = new JTextPane();

//initialize data in arrays
String title[] = {"Casablanca", "Citizen Kane", "Singin' in the Rain", "The Wizard of Oz"};
String studio[] = {"Warner Brothers", "RKO Pictures", "MGM", "MGM" };
String year[] = {"1942", "1941", "1952", "1939"};

//construct instance of DVD
public DVD()
{
super("Classics on DVD");
}

//create the menu system
public JMenuBar createMenuBar()
{
//create an instance of the menu
JMenuBar mnuBar = new JMenuBar();
setJMenuBar(mnuBar);

//construct and populate the File menu
JMenu mnuFile =new JMenu("File", true);
mnuFile.setMnemonic(KeyEvent.VK_F);
mnuFile.setDisplayedMnemonicIndex(0);
mnuBar.add(mnuFile);


JMenuItem mnuFileOpen = new JMenuItem("Open");
mnuFileOpen.setMnemonic(KeyEvent.VK_O);
mnuFileOpen.setDisplayedMnemonicIndex(0);
mnuFile.add(mnuFileOpen);
mnuFileOpen.setActionCommand("Open");
mnuFileOpen.addActionListener(this);

JMenuItem mnuFileExit = new JMenuItem("Exit");
mnuFileExit.setMnemonic(KeyEvent.VK_X);
mnuFileExit.setDisplayedMnemonicIndex(1);
mnuFile.add(mnuFileExit);
mnuFileExit.setActionCommand("Exit");
mnuFileExit.addActionListener(this);



//construct and populate the Edit menu
JMenu mnuEdit = new JMenu("Edit", true);
mnuEdit.setMnemonic(KeyEvent.VK_E);
mnuEdit.setDisplayedMnemonicIndex(0);
mnuBar.add(mnuEdit);

JMenuItem mnuEditInsert = new JMenuItem("Insert New DVD");
mnuEditInsert.setMnemonic(KeyEvent.VK_I);
mnuEditInsert.setDisplayedMnemonicIndex(0);
mnuEdit.add(mnuEditInsert);
mnuEditInsert.setActionCommand("Insert");
mnuEditInsert.addActionListener(this);

JMenu mnuEditSearch = new JMenu("Search");
mnuEditSearch.setMnemonic(KeyEvent.VK_R);
mnuEditSearch.setDisplayedMnemonicIndex(3);
mnuEdit.add(mnuEditSearch);

JMenuItem mnuEditSearchByTitle = new JMenuItem("by Title");
mnuEditSearchByTitle.setMnemonic(KeyEvent.VK_T);
mnuEditSearchByTitle.setDisplayedMnemonicIndex(3);
mnuEditSearch.add(mnuEditSearchByTitle);
mnuEditSearchByTitle.setActionCommand("title");
mnuEditSearchByTitle.addActionListener(this);

JMenuItem mnuEditSearchByStudio = new JMenuItem("by Studio");
mnuEditSearchByStudio.setMnemonic(KeyEvent.VK_S);
mnuEditSearchByStudio.setDisplayedMnemonicIndex(3);
mnuEditSearch.add(mnuEditSearchByStudio);
mnuEditSearchByStudio.setActionCommand("studio");
mnuEditSearchByStudio.addActionListener(this);

JMenuItem mnuEditSearchByYear = new JMenuItem("by Year");
mnuEditSearchByYear.setMnemonic(KeyEvent.VK_Y);
mnuEditSearchByYear.setDisplayedMnemonicIndex(3);
mnuEditSearch.add(mnuEditSearchByYear);
mnuEditSearchByYear.setActionCommand("year");
mnuEditSearchByYear.addActionListener(this);

return mnuBar;
}

//create the content pane
public void createContentPane()
{
//populate the JComboBox
fieldCombo.addItem("Title");
fieldCombo.addItem("Studio");
fieldCombo.addItem("Year");
fieldCombo.addActionListener(this);
fieldCombo.setToolTipText("Click the drop down arrow to display sort fields.");

//construct and populate the north panel
JPanel northPanel = new JPanel();
northPanel.setLayout(new FlowLayout());
northPanel.add(sortPrompt);
northPanel.add(fieldCombo);

//create the JTextPane and center panel
JPanel centerPanel = new JPanel();
setTabsAndStyles(textPane);
textPane = addTextToTextPane();
JScrollPane scrollPane = new JScrollPane(textPane);
scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
scrollPane.setPreferredSize(new Dimension(500, 200));
centerPanel.add(scrollPane);

//create Container and set attributes
// Container c = getContentPane();
setLayout(new BorderLayout(10,10));
add(northPanel,BorderLayout.NORTH);
add(centerPanel,BorderLayout.CENTER);

// return c;
}

//method to create tab stops and set font styles
protected void setTabsAndStyles(JTextPane textPane)
{
//create Tab Stops
TabStop[] tabs = new TabStop[2];
tabs[0] = new TabStop(200, TabStop.ALIGN_LEFT, TabStop.LEAD_NONE);
tabs[1] = new TabStop(350, TabStop.ALIGN_LEFT, TabStop.LEAD_NONE);
TabSet tabset = new TabSet(tabs);

//set Tab Style
StyleContext tabStyle = StyleContext.getDefaultStyleContext();
AttributeSet aset =
tabStyle.addAttribute(SimpleAttributeSet.EMPTY, StyleConstants.TabSet, tabset);
textPane.setParagraphAttributes(aset, false);

//set Font Style
Style fontStyle =
StyleContext.getDefaultStyleContext().getStyle(StyleContext.DEFAULT_STYLE);

Style regular = textPane.addStyle("regular", fontStyle);
StyleConstants.setFontFamily(fontStyle, "SansSerif");

Style s = textPane.addStyle("italic", regular);
StyleConstants.setItalic(s, true);

s = textPane.addStyle("bold", regular);
StyleConstants.setBold(s, true);

s = textPane.addStyle("large", regular);
StyleConstants.setFontSize(s, 16);
}

//method to add new text to the JTextPane
public JTextPane addTextToTextPane()
{
Document doc = textPane.getDocument();
try
{
//clear previous text
doc.remove(0, doc.getLength());

//insert title
doc.insertString(0,"TITLE\tSTUDIO\tYEAR\n",textPane.getStyle("large"));

//insert detail
for (int j = 0; j<title.length; j++)
{
doc.insertString(doc.getLength(), title[j] + "\t", textPane.getStyle("bold"));
doc.insertString(doc.getLength(), studio[j] + "\t", textPane.getStyle("italic"));
doc.insertString(doc.getLength(), year[j] + "\n", textPane.getStyle("regular"));
}
}
catch(BadLocationException ble)
{
System.err.println("Couldn't insert text.");
}

return textPane;
}

//event to process user clicks
public void actionPerformed(ActionEvent e)
{
String arg = e.getActionCommand();

//user clicks the sort by combo box
if (e.getSource() == fieldCombo)
{
switch (fieldCombo.getSelectedIndex())
{
case 0:
sort(title);
break;
case 1:
sort(studio);
break;
case 2:
sort(year);
break;
}
}

//user clicks Exit on the File menu
if (arg == "Exit")
System.exit(0);

//user clicks Insert new DVD on the Edit menu
if (arg == "Insert")
{
//accept new data
String newTitle = JOptionPane.showInputDialog(null, "Please enter the new movie's title");
String newStudio = JOptionPane.showInputDialog(null, "Please enter the studio for " + newTitle);
String newYear = JOptionPane.showInputDialog(null, "Please enter the year for " + newTitle);

//enlarge arrays
title = enlargeArray(title);
studio = enlargeArray(studio);
year = enlargeArray(year);

//add new data to arrays
title[title.length-1] = newTitle;
studio[studio.length-1] = newStudio;
year[year.length-1] = newYear;

//call sort method
sort(title);
fieldCombo.setSelectedIndex(0);
}

//user clicks Title on the Search submenu
if (arg == "title")
search(arg, title);

//user clicks Studio on the Search submenu
if (arg == "studio")
search(arg, studio);

//user clicks Year on the Search submenu
if (arg == "year")
search(arg, year);
}

//method to enlarge an arry by 1
public String[] enlargeArray(String[] currentArray)
{
String[] newArray = new String[currentArray.length +1];
for (int i = 0; i<currentArray.length; i++)
newArray[i] = currentArray[i];
return newArray;
}

//method to sort arrays
public void sort(String tempArray[])
{
// loop to control number of passes
for (int pass = 1; pass < tempArray.length; pass++)
{
for (int element = 0; element < tempArray.length - 1; element++)
if (tempArray[element].compareTo(tempArray[element + 1])>0)
{
swap(title, element, element + 1);
swap(studio, element, element + 1);
swap(year, element, element + 1);
}
}
addTextToTextPane();
}

// method to swap two elements of an array
public void swap(String swapArray[], int first, int second)
{
String hold; // temporary holding area for swap
hold = swapArray[first];
swapArray[first] = swapArray[second];
swapArray[second] = hold;
}

public void search(String searchField, String searchArray[])
{
try
{
Document doc = textPane.getDocument(); //assign text to document object
doc.remove(0,doc.getLength()); //clear previous text

//display column titles
doc.insertString(0,"TITLE\tSTUDIO\tYEAR\n",textPane.getStyle("large"));

//prompt user for search data
String search = JOptionPane.showInputDialog(null, "Please enter the "+ searchField);
boolean found = false;

//search arrays
for (int i = 0; i<title.length; i++)
{
if (search.compareTo(searchArray[i])==0)
{
doc.insertString(doc.getLength(), title[i] + "\t", textPane.getStyle("bold"));
doc.insertString(doc.getLength(), studio[i] +"\t",textPane.getStyle("italic"));
doc.insertString(doc.getLength(), year[i] + "\n", textPane.getStyle("regular"));
found = true;
}
}
if (found == false)
{
JOptionPane.showMessageDialog(null, "Your search produced no results.","No results found",JOptionPane.INFORMATION_MESSAGE);
sort(title);
}
}
catch(BadLocationException ble)
{
System.err.println("Couldn't insert text.");
}
}

public void OpenFile()
{
Date today = new Date();
//SimpleDateFormat myFormat = new SimpleDateFormat("MMddyyyy");
String filename = "payments" /*+ myFormat.format(today)*/;
try
{
output = new DataOutputStream(new FileOutputStream(filename));

}
catch(IOException io)
{
JOptionPane.showMessageDialog(null,"The program could not create a storage location. Please check the disk drive and then run the program again.","Error",JOptionPane.INFORMATION_MESSAGE);

System.exit(1);
}
addWindowListener(
new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
int answer = JOptionPane.showConfirmDialog(null, "Are you sure you want to exit and submit the file?", "File Submission", JOptionPane.YES_NO_OPTION);
if (answer == JOptionPane.YES_OPTION)
System.exit(0);
}
}
);
}
public void actionFileOutput(ActionEvent e)
{
String arg = e.getActionCommand();

try
{
for(int i=0; i<title.length; i++)
{
output.writeChars(title[i]+"\t");
output.writeChars(studio[i]+"\t");
output.writeChars(year[i]+"\n");
}
JOptionPane.showMessageDialog(null,"The payment information has been saved.","Submission Successful",JOptionPane.INFORMATION_MESSAGE);
}
catch(IOException c)
{
System.exit(1);
}

}


//main method executes at run time
public static void main(String args[])
{
JFrame.setDefaultLookAndFeelDecorated(true);
DVD f = new DVD();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE );
f.setJMenuBar(f.createMenuBar());
f.createContentPane();
f.setSize(600,375);
f.setVisible(true);
}
}

Advertisement
View Answers

Related Tutorials/Questions & Answers:
Creating a File I/O using import scanner, io.* and text.*
Creating a File I/O using import scanner, io.* and text.*  open a file for reading and open another file for writing data. input file hours-int, hourly rate-double, name-string. output file name-string, hours-int, hourly rate
Java I\O file
Java I\O file  What is the difference between the File and RandomAccessFile classes
Advertisements
File I/O
File I/O  i am trying to read and write a 54mb text file from one directory to another. I managed to do it perfectly using the examples i was given... question is, is their away i can read and write in the shortes time possible(in seconds
File I/O
File I/O  i am trying to write a program that reads a text file... the text file then read it and write it into as a comma delimitade file. i have... with "tAC" and ends with "->0|0|6" as you shall see in the text file i have
File I/O
File I/O  greetings i was running into a problem. is their a way...(); File[] files = file.listFiles(filter); for (int i = 0; i <... java.io.IOException{ File file = new File("C:/Text/"); FilenameFilter filter
File I/O
File I/O  i have a problem i am trying to print on a new line every time i reach a certain condition "if(line.startsWith("Creating"))" i want... = file.listFiles();//listFiles all file in inpath dir for (int i = 0; i <
file I/O
file I/O  Write a java class which it should do below Read the attached file. Sorted out and writer it into another file(sorted values). Also find the SECOND biggest number in the attached file
File I/O
File I/O  i am trying to read and write a file. my program works perfectly i am using PrintWriter and BufferedReader. but my problem is that when... like this input file blahblah i am a computer i am running windows i am
file i/o - Java Beginners
file i/o  hiii, i have to read some integers from a text file and store them in link list.. so please can i have source code for it.?? thanks
File I/O - Java Beginners
File I/O  Suppose a text file has 10 lines.How do I retrieve... and send a text file as argument. ============================== import... oi oiu 25 ewr ytro 9+ po I want to retrieve 'abc' 'fg' .... 'yt' 'ewr
File I/O - Java Beginners
File I/O  How to search for a specific word in a text file in java?  Hi Arnab, Please check the following code...[]){ String searchString = args[1].toLowerCase(); try { File fileName = new File
i/o
i/o   Write a Java program to do the following: a. Write into file the following information regarding the marks for 10 students in a test i... the file and calculate the average for each question and for total marks. Determine
java i/o operations
java i/o operations  how to write integer data to a file in java using random access file object or file writer or data outputstream i have already tried the write and writeInt methods....plz help
I/O stream class.
I/O stream class.  Explain the hierarchy of Java I/O stream class.   Hierarchy of Java I/O streams Have a look at the following link: Java I/O
Java i/o
Java i/o   How can you improve Java I/O performance
Java i/o opearations
Java i/o opearations  "FOLLOWING IS MY LAST QUESTION ON JAVA I/O... to a file in java using random access file object or file writer or data outputstream i... STREAM BUT IT IS NOT WORKING WELL WITH RANDOM ACCESS FILE" i.e.,how to WRITE integer
i/o streamas
i/o streamas  java program using bufferedreader and bufferedwriter   Hi Friend, Try the following code: import java.io.*; class...(line); out.newLine(); } out.close(); System.out.println("File
Java I/O problem
Java I/O problem   Write a Java application that prompts the user... the standard input - this information should then be saved to a file named studentData... to handle the data output. Create a separate class to read in that file, line
Java I/O stream
Java I/O stream  What class allows you to read objects directly from a stream
Java I/O
Java I/O   What is the difference between the Reader/Writer class hierarchy and the InputStream/OutputStream class hierarchy
I/O Java
I/O Java  import java.io.File; import java.io.FileNotFoundException...); } }else{ System.out.println("File name must be a TEXT...(File file) { //if the file extension is .txt or .java return true, else
I/O to another applications
I/O to another applications  **What if there exists an application...); System.out.print("Enter integer: "); int i=input.nextInt...(); System.out.println(i); System.out.println(d); System.out.println(f
Java I/O
Java I/O  What value does readLine() return when it has reached the end of a file
Java I/O
Java I/O  how to write different type of arrays like string,int,double etc into a file using DataOutputStream
I/O Program output error
file, but I am getting incorrect output. I have been successfull with part of the program in that it reads the text file and analyzes it, however I need it to take...I/O Program output error  Hello All, I am working on a program
Java I/O Assistance + Loop
Java I/O Assistance + Loop  I'm trying to make this program write file numbers.dat that's accomplished. I'm also trying to make it write all even... and append all odd numbers 1-100 and finally close file. But for some reason I
Java I/O - Java Beginners
Creating Directory Java I/O  Hi, I wanted to know how to create a directory in Java I/O?  Hi, Creating directory with the help of Java.../java  yeah i konw tht method but i want another program whr we shld nt use
java i/o - Java Beginners
text:" then that text gets saved in a file called "data.txt" and then program gets closed. when i open the program again and enter text in this case previous texts get replaced with new text. i tried my best but got failed plz tell me
Java I/O Character Streams
is used for output (write to). To work with the file I/O specialized classes...Java I/O Character Streams In this section we will discuss the I/O Character... and for this Java provides the Character stream I/O. Character stream I/O
java i/o - Java Beginners
java i/o  thnx alot sir that this code helped me much in my program but still i'm facing a problem that it writes in file in this way- Hello... so that i could write it line by line such as- Hello Java in roseindia Hello
Java I/O Byte Streams
Java I/O Byte Streams In this section we will discussed the I/O Byte Streams... I/O raw binary data the byte stream classes are defined. For all of the byte... bytes from a file. ByteArrayInputStream A ByteArrayInputStream can retain
Java I/O Buffered Streams
Java I/O Buffered Streams In this section we will discuss the I/O Buffered... : In an unbuffered way the read and write operations are performed by the O/S...; readLine() : This method is used to read the line of text. public String readLine
Java I/O Examples
provides the standard I/O facilities for reading text through either...; What is Java I/O? The Java I/O means... and Interfaces of the I/O Streams The following listing of classes
find a substring by using I/O package
find a substring by using I/O package  Write a java program to find a sub string from given string by using I/O package
i/o
i/o  java program using inputstream and outputstream   Hi Friend, Try the following code: import java.io.*; class InputStreamAndOutputStream { public static void main(String[] args)throws
i/o
i/o  java program using inputstream and outputstream   Hi Friend, Try the following code: import java.io.*; class InputStreamAndOutputStream { public static void main(String[] args)throws Exception
i/o
i/o  java program using inputstream and outputstream   Hi Friend, Try the following code: import java.io.*; class InputStreamAndOutputStream { public static void main(String[] args)throws Exception
i/o
i/o  java program using inputstream and outputstream   Hi Friend, Try the following code: import java.io.*; class InputStreamAndOutputStream { public static void main(String[] args)throws Exception
Classes and Interfaces of the I/O Streams
Classes and Interfaces of the I/O Streams   ... then this exception to be occured. InterruptedIOException When the I/O... When the I/O operations to be failed then it occurs. NotActiveException
Java I/O
JAVA I/O Introduction The Java Input/Output (I/O) is a part of java.io package. The java.io package contains a relatively large number of classes that support  input and output operations. The classes in the package are primarily
Java I/O Data Streams
Java I/O Data Streams In this tutorial we will discuss the Java I/O Data Streams. To deal with the binary I/O of primitive data type values as well... and write to a random access file. ObjectInputStream ObjectInputStream
text file
text file  Hello can I modify the program below so that all the numerical data is stored in an external text file,that is the data contained...(); System.out.print("ADDRESS-3:"); String o=in.nextLine(); System.out.print("POST
Java I/O From the Command Line
Java I/O From the Command Line In this section we will learn about the I/O...() This method is used to read a line of text from the console. readLine(String fmt, Object... args) This method is used to read a line of text from
text file
text file  Hi can you help me I have to modify the program below so that all the data held in it is stored in an external text file.So there should... at the start of the program from a seperate external text file.Thank you! mport
Read Text from Standard IO
from the keyboard and write output to the display. They also support I/O...); Working with Reader classes: Java provides the standard I/O facilities for reading text from either the file or the keyboard on the command
Write a program that replaces a, e, i, o, u in Java2
Write a program that replaces a, e, i, o, u in Java2  Write a program that replaces a, e, i, o, u, with the letter z. (i.e. John Smith -> Jzhn Smzth. Also the program reverses the users name (i.e. John Smith -> htimS nhoJ
Reading a text file in java
Reading a text file in java  What is the code for Reading a text file... 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
Convert Text File to PDF file
Convert Text File to PDF file  Here is the way how to covert your Text file to PDF File, public class TextFileToPDF { private static void...(inLine); System.out.println("Text is inserted into pdf file
Sorting text file
local website. i'm storing all file list in text file. And also adding a value to each line at the beginning. now i want to sort file content in descending order according to begin value. Text File having list like this: 5| 3| can anyone
inserting text into text file using java application
inserting text into text file using java application  Hi, I want to insert a text or string into a text file using java application
 

 

 

DMCA.com