// call this method to write the description to the file // the file pointer must be already positioned // the description must have been set private void writeDescription() throws IOException { if (description.length() > DESCRIPTION_LENGTH) description = description.substring(0, DESCRIPTION_LENGTH); outStream.writeChars(description); for (int j = 0; j < (DESCRIPTION_LENGTH - description.length()); j++) outStream.writeChar(' '); }
/** * Writes the Item location to the Items Random Access File * * @param file - the Item's Random Access File */ private void writeLocationToFile(RandomAccessFile file) { try { file.writeByte(1); // Write the warehouse number file.writeByte(getLocation().getAisle()); // Write the aisle number file.writeByte(getLocation().getColumn()); // Write the column number file.writeChar(getLocation().getRow()); // Write the row number } catch (Exception e) { } }
// call this method to write the column names to the file // the file pointer must be already positioned private void writeColumnNames(ArrayList names) throws IOException { String column; for (int i = 0, numCols = names.size(); i < numCols; i++) { column = (String) names.get(i); if (column.length() > COLUMN_LENGTH) column = column.substring(0, COLUMN_LENGTH); outStream.writeChars(column); for (int j = 0; j < (COLUMN_LENGTH - column.length()); j++) outStream.writeChar(' '); } }
public static void main(String args[]) { try { String fname = "d:\\q.txt"; String mode; // mode = "r";//r : file must exist mode = "rw"; // rw : file will be created or opened // open the file RandomAccessFile raf = new RandomAccessFile(fname, mode); /* //seek and write demo raf.seek(10);//position file r/w pointer at index 10 wrt BOF //a seek beyond file size causes file to grow upto the seek value raf.write(65);//raf.write('A'); */ // r/w java datatypes int i1, i2; float f1, f2; char c1, c2; String s1, s2; i1 = -10; f1 = 1234.5678F; c1 = 'q'; s1 = "hello files"; raf.seek(0); // reach BOF raf.writeInt(i1); raf.writeFloat(f1); raf.writeChar(c1); raf.writeUTF(s1); raf.seek(0); // reach BOF i2 = raf.readInt(); f2 = raf.readFloat(); c2 = raf.readChar(); s2 = raf.readUTF(); System.out.println(i2); System.out.println(f2); System.out.println(c2); System.out.println(s2); // close the file raf.close(); } catch (IOException ex) { System.out.println(ex); // ex converts into ex.toString() } } // main