Off Topic Cafe If it doesn't belong in any of the other forums. Post all Off Topic stuff here.

JAVAGEEK!!! and other programmers

Thread Tools
 
Old 02-01-2005, 10:24 PM
  #1  
Senior Member
Thread Starter
 
djshaggy's Avatar
 
Join Date: Nov 2004
Location: Dallas, TX
Posts: 174
Likes: 0
Received 0 Likes on 0 Posts
Default JAVAGEEK!!! and other programmers

ok ok I know this is a car forum, but I need some help...

I need help with some I/O operations using java's RandomAccessFile class.

I have the data written and I can access any record I want, but I can't figure out how to delete a record from the file easily when I don't want it anymore. I also need to update records but I think if I know how to delete, I can figure out how to update.

Do you know of a better java I/O object class that would be better than RandomAccessFile, or do you have any sample programs that you could show me.

Any help is appriciated.
Old 02-01-2005, 10:38 PM
  #2  
Senior Member
 
javageek's Avatar
 
Join Date: Jul 2001
Location: Clovis, NM
Posts: 7,063
Likes: 0
Received 0 Likes on 0 Posts
Vehicle: 2010 Jeep Wrangler Unlimited
Default

Java= Coffee
Geek= Computers

Future aspirations: Open an Internet Cafe' featuring gourmet coffees from around the world and high speed internet access for the clientele.

Sorry, I don't program Java yet. If the Air Force decides to cross train me I can help you out. laugh.gif:
Old 02-01-2005, 10:42 PM
  #3  
Senior Member
Thread Starter
 
djshaggy's Avatar
 
Join Date: Nov 2004
Location: Dallas, TX
Posts: 174
Likes: 0
Received 0 Likes on 0 Posts
Default

well thanx for the clarification on your name..lol oops.gif

I guess I will just banghead.gif until I get this figured out....I wish there were some Java programmers in here lol
Old 02-01-2005, 10:47 PM
  #4  
Senior Member
 
a_gut's Avatar
 
Join Date: Jun 2004
Location: Phoenix, AZ
Posts: 575
Likes: 0
Received 0 Likes on 0 Posts
Default

Tried writing a null string to whatever you want to erase?
Old 02-01-2005, 10:51 PM
  #5  
Administrator
 
majik's Avatar
 
Join Date: Oct 2002
Location: ɯooɹpǝq ɹnoʎ
Posts: 13,943
Likes: 0
Received 0 Likes on 0 Posts
Vehicle: ǝdnoɔ sısǝuǝƃ
Default

I'm not familiar with RandomAccessFiles. I'm in my second semester of Java programming... what program are you using to code it?
What exactly are you trying to program? Do you have any sources of reference?

http://java.sun.com/j2se/1.4.2/docs/api/index.html
http://java.sun.com/j2se/1.4.2/docs/api/ja...AccessFile.html - more specifically
Old 02-01-2005, 10:52 PM
  #6  
Senior Member
Thread Starter
 
djshaggy's Avatar
 
Join Date: Nov 2004
Location: Dallas, TX
Posts: 174
Likes: 0
Received 0 Likes on 0 Posts
Default

I have tired to write a null object to what I want to erase however I just create a new null record instead of writing over a record. (I am writing serialized objects to the file)


Do you know of a better I/O file class in Java I can use instead of RandomAccessFile, because this is giving me a headache..mad.gif

Edited for majiktib's response

I use notepad and the javac compiler in the CMD

I am writing a program to create a database file for Addresses for my Java class, and I have to be able to enter new records delete records and edit records all in GUI and then display in a table sorted by any field the user wants.

Everything works now except the delete and edit, but I am considering using a different java class for I/O if I can't get this to work, which means starting all over.
Old 02-02-2005, 06:36 AM
  #7  
Senior Member
 
Omega's Avatar
 
Join Date: Sep 2004
Location: Montreal, Qc, Canada
Posts: 175
Likes: 0
Received 0 Likes on 0 Posts
Default

By definition, a random access file will do what you just explained.

You "can't" delete a record in a random access file, well, with the basic library and tools available.

You know MS Access? You know the "Compact Database" command? This is exactly what you need to do.

When you "erase" a record, you are actually flagging it as "erased". After a while, your file grows bigger and you need a way to clean it. You must then "compact" your file by removing the flagged record physically from the file.

Hope it helps.
Old 02-02-2005, 09:37 AM
  #8  
Senior Member
Thread Starter
 
djshaggy's Avatar
 
Join Date: Nov 2004
Location: Dallas, TX
Posts: 174
Likes: 0
Received 0 Likes on 0 Posts
Default

Omega, That sounds perfect!

I will get to coding and let you guys know how it turns out...
...if you care or not tongue.gif:
Old 02-02-2005, 02:13 PM
  #9  
Administrator
 
majik's Avatar
 
Join Date: Oct 2002
Location: ɯooɹpǝq ɹnoʎ
Posts: 13,943
Likes: 0
Received 0 Likes on 0 Posts
Vehicle: ǝdnoɔ sısǝuǝƃ
Default

I suggest you get TextPad.. works great.

Here are 3 files that came with my Murach's Java II Book. They are book examples and seem to do exactly what you're dealing with now. I'm not sure how to put them into a table, but these have an Add, Update, Delete feature.

Book.java:
CODE

import java.io.*;
public class Book{
private String code;
private String title;
private double price;
public Book(String bookCode, String bookTitle, double bookPrice){
code = bookCode;
title = bookTitle;
price = bookPrice;
}
public Book(String bookCode) throws IOException{
code = bookCode;
Book tempBook = BookIO.readRecord(bookCode);
title = tempBook.getTitle();
price = tempBook.getPrice();
}
public String getCode(){ return code; }
public String getTitle(){ return title; }
public double getPrice(){ return price; }
}

BookFrame.java:
CODE
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import java.text.*;
import java.io.*;
public class BookFrame extends JFrame{
public BookFrame(){
setTitle("Book Maintenance");
Toolkit tk = Toolkit.getDefaultToolkit();
Dimension d = tk.getScreenSize();
int width = 400, height = 200;
setBounds((d.width - width)/2, (d.height - height)/2, width, height);
setResizable(false);
addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
BookIO.close();
System.exit(0);
}
});
Container contentPane = getContentPane();
BookPanel panel = new BookPanel();
contentPane.add(panel);
}
public static void main(String[] args){
JFrame frame = new BookFrame();
frame.show();
}
}
class BookPanel extends JPanel implements ActionListener,
DocumentListener, KeyListener{
private JButton addButton, updateButton, deleteButton, exitButton,
firstButton, prevButton, nextButton, lastButton;
private JLabel codeLabel, titleLabel, priceLabel;
private JTextField codeField, titleField, priceField;
private boolean addFlag = false;
private NumberFormat currency = NumberFormat.getCurrencyInstance();
private Book currentBook = null;
public BookPanel(){
codeLabel = new JLabel("Code: ");
codeField = new JTextField("", 7);
titleLabel = new JLabel("Title: ");
titleField = new JTextField("", 26);
priceLabel = new JLabel("Price: ");
priceField = new JTextField("", 7);
JPanel updatePanel = new JPanel();
addButton = new JButton("Add");
updateButton = new JButton("Update");
deleteButton = new JButton("Delete");
exitButton = new JButton("Exit");
updatePanel.add(addButton);
updatePanel.add(updateButton);
updatePanel.add(deleteButton);
updatePanel.add(exitButton);
JPanel navigationPanel = new JPanel();
firstButton = new JButton("First");
prevButton = new JButton("Prev");
nextButton = new JButton("Next");
lastButton = new JButton("Last");
navigationPanel.add(firstButton);
navigationPanel.add(prevButton);
navigationPanel.add(nextButton);
navigationPanel.add(lastButton);
addButton.addActionListener(this);
updateButton.addActionListener(this);
deleteButton.addActionListener(this);
exitButton.addActionListener(this);
firstButton.addActionListener(this);
prevButton.addActionListener(this);
nextButton.addActionListener(this);
lastButton.addActionListener(this);
codeField.addKeyListener(this);
titleField.addKeyListener(this);
priceField.addKeyListener(this);
titleField.getDocument().addDocumentListener(thi s);
priceField.getDocument().addDocumentListener(thi s);
setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
c.weightx = 100;
c.weighty = 100;
c.ipadx = 5;
c.anchor = GridBagConstraints.EAST;
c = getConstraints(c, 1, 1, 1, 1);
add(codeLabel, c);
c = getConstraints(c, 1, 2, 1, 1);
add(titleLabel, c);
c = getConstraints(c, 1, 3, 1, 1);
add(priceLabel, c);
c.anchor = GridBagConstraints.WEST;
c = getConstraints(c, 2, 1, 3, 1);
add(codeField, c);
c = getConstraints(c, 2, 2, 3, 1);
add(titleField, c);
c = getConstraints(c, 2, 3, 3, 1);
add(priceField, c);
c.anchor = GridBagConstraints.CENTER;
c = getConstraints(c, 1, 4, 4, 1);
add(updatePanel, c);
c = getConstraints(c, 1, 5, 4, 1);
add(navigationPanel, c);
try{
BookIO.open();
currentBook = BookIO.moveFirst();
}
catch (FileNotFoundException e){
JOptionPane.showMessageDialog(null, "FileNotFoundException");
System.exit(1);
}
catch (IOException e){
JOptionPane.showMessageDialog(null, "IOException");
}
performBookDisplay();
enableButtons(true);
}
private GridBagConstraints getConstraints(GridBagConstraints c,
int x, int y, int width, int height){
c.gridx = x;
c.gridy = y;
c.gridwidth = width;
c.gridheight = height;
return c;
}
private void performBookDisplay(){
codeField.setText(currentBook.getCode());
titleField.setText(currentBook.getTitle());
priceField.setText(currency.format(currentBook.g etPrice()));
}
private void enableButtons(boolean flag1){
boolean flag2 = false;
if (flag1 == false) flag2 = true;
updateButton.setEnabled(flag2);
addButton.setEnabled(flag1);
deleteButton.setEnabled(flag1);
firstButton.setEnabled(flag1);
nextButton.setEnabled(flag1);
prevButton.setEnabled(flag1);
lastButton.setEnabled(flag1);
}
public void actionPerformed(ActionEvent e){
try{
Object source = e.getSource();
if (source == exitButton){
BookIO.close();
System.exit(0);
}
else if (source == firstButton){
currentBook = BookIO.moveFirst();
performBookDisplay();
enableButtons(true);
}
else if (source == prevButton){
currentBook = BookIO.movePrevious();
performBookDisplay();
enableButtons(true);
}
else if (source == nextButton){
currentBook = BookIO.moveNext();
performBookDisplay();
enableButtons(true);
}
else if (source == lastButton){
currentBook = BookIO.moveLast();
performBookDisplay();
enableButtons(true);
}
else if (source == addButton){
codeField.requestFocus();
enableButtons(false);
codeField.setText("");
titleField.setText("");
priceField.setText("");
addFlag = true;
}
else if (source == updateButton){
String priceString = priceField.getText();
if (priceString.charAt(0) == '$')
priceString = priceString.substring(1);
double price = Double.parseDouble(priceString);
Book book = new Book(codeField.getText(),
titleField.getText(), price);
if (addFlag == false){
BookIO.updateRecord(book);
}
if (addFlag == true){
BookIO.addRecord(book);
addFlag = false;
}
currentBook = book;
performBookDisplay();
enableButtons(true);
}
else if(source == deleteButton){
BookIO.deleteRecord(currentBook.getCode( ));
nextButton.requestFocus();
nextButton.doClick();
}
}
catch (FileNotFoundException fnfe){
JOptionPane.showMessageDialog(this, "FileNotFoundException");
}
catch (NumberFormatException nfe){
JOptionPane.showMessageDialog(this, "NumberFormatException");
}
catch (IOException ioe){
JOptionPane.showMessageDialog(this, "IOException");
}
}
public void keyPressed(KeyEvent e){
int keyCode = e.getKeyCode();
if (keyCode == KeyEvent.VK_ESCAPE){
codeField.requestFocus();
performBookDisplay();
enableButtons(true);
}
}
public void keyReleased(KeyEvent e){}
public void keyTyped(KeyEvent e){}
public void insertUpdate(DocumentEvent e){
enableButtons(false);
}
public void removeUpdate(DocumentEvent e){
enableButtons(false);
}
public void changedUpdate(DocumentEvent e){}
}
Old 02-02-2005, 02:14 PM
  #10  
Administrator
 
majik's Avatar
 
Join Date: Oct 2002
Location: ɯooɹpǝq ɹnoʎ
Posts: 13,943
Likes: 0
Received 0 Likes on 0 Posts
Vehicle: ǝdnoɔ sısǝuǝƃ
Default

BookIO.java:
CODE

import java.io.*;
import java.util.*;
public class BookIO{
private static Book book = null;
private static String[] codes = null;
private static RandomAccessFile randomFile = null;
private static final File BOOK_FILE = new File("books.dat");
private static final int CODE_SIZE = 4;
private static final int TITLE_SIZE = 20;
private static final int RECORD_SIZE = CODE_SIZE*2 + TITLE_SIZE*2 + 8;
public static void open() throws IOException{
randomFile = new RandomAccessFile(BOOK_FILE, "rw");
codes = readCodes();
}
public static void close(){
try{
randomFile.close();
}
catch(IOException e){
System.out.println("I/OException thrown when closing file.");
}
}
public static int getRecordCount() throws IOException{
long length = BOOK_FILE.length();
int recordCount = (int) (length / RECORD_SIZE);
return recordCount;
}
public static String readString(DataInput in, int length)
throws IOException{
String s = "";
int i = 0;
while (i < length){
char c = in.readChar();
if (c!=0)
s += c;
i++;
}
return s;
}
public static Book readRecord(int recordNumber) throws IOException{
randomFile.seek((recordNumber-1) * RECORD_SIZE);
String code = readString(randomFile, CODE_SIZE);
String title = readString(randomFile, TITLE_SIZE);
double price = randomFile.readDouble();
book = new Book(code, title, price);
return book;
}
public static Book readRecord(String bookCode) throws IOException{
int recordNumber = getRecordNumber(bookCode);
book = readRecord(recordNumber);
return book;
}
public static int getRecordNumber(String bookCode) throws IOException{
int match = -1;
int i = 0;
boolean flag = true;
while ((i < getRecordCount()) && (flag==true)){
if (bookCode.equals(codes[i])){
match = i+1;
flag = false;
}
i++;
}
return match;
}
public static String[] readCodes() throws IOException{
codes = new String[getRecordCount()];
for (int i = 0; i < getRecordCount(); i++){
randomFile.seek(i * RECORD_SIZE);
codes[i] = readString(randomFile, CODE_SIZE);
}
return codes;
}
public static String[] readTitles() throws IOException{
String[] titles = new String[getRecordCount()];
for (int i = 0; i < getRecordCount(); i++){
randomFile.seek(i * RECORD_SIZE + 8);
titles[i] = readString(randomFile, TITLE_SIZE);
}
return titles;
}
public static void writeString(DataOutput out, String s, int length)
throws IOException{
for (int i = 0; i < length; i++){
if (i < s.length())
out.writeChar(s.charAt(i));
else
out.writeChar(0);
}
}
public static void writeRecord(Book book, int recordNumber)
throws IOException{
randomFile.seek((recordNumber-1) * RECORD_SIZE);
writeString(randomFile, book.getCode(), CODE_SIZE);
writeString(randomFile, book.getTitle(), TITLE_SIZE);
randomFile.writeDouble(book.getPrice());
}
public static Book moveFirst() throws IOException{
book = readRecord(1);
return book;
}
public static Book movePrevious() throws IOException{
int recordNumber = getRecordNumber(book.getCode());
if (recordNumber != 1)
book = readRecord(recordNumber - 1);
return book;
}
public static Book moveNext() throws IOException{
int recordNumber = getRecordNumber(book.getCode());
if (recordNumber != getRecordCount())
book = readRecord(recordNumber + 1);
return book;
}
public static Book moveLast() throws IOException{
int lastRecordNumber = getRecordCount();
book = readRecord(lastRecordNumber);
return book;
}
public static void addRecord(Book addBook) throws IOException{
writeRecord(addBook, getRecordCount() + 1);
close();
open();
}
public static void updateRecord(Book book) throws IOException{
int recordNumber = getRecordNumber(book.getCode());
writeRecord(book, recordNumber);
}
public static void deleteRecord(String bookCode) throws IOException{
int recordNumber = getRecordNumber(bookCode);
Vector books = new Vector();
for (int i = 0; i< getRecordCount(); i++){
books.add(readRecord(i+1));
}
books.remove(recordNumber-1);
randomFile.setLength(RECORD_SIZE *(getRecordCount() -1));
for (int i = 0; i



All times are GMT -6. The time now is 10:16 PM.