Zur Demonstration der wahlfreien Dateibearbeitung werden zwei Beispiele herangezogen. Das erste Programm löst die Aufgabe, einen oder mehrere Sätze aus einer SAM-Datei zu löschen. Das Programm erwartet dazu als Parameter den Namen einer existierenden Datei und die Nummer oder den Nummernbereich der Datensätze, die gelöscht werden sollen. Beachten Sie, dass auch hier Datensätze mit Null beginnend durchnummeriert werden.
Das Beispiel ist so angelegt, dass man keine Kenntnisse über die Dateiattribute, wie Satzformat oder Satzlänge, der zu bearbeitenden Datei benötigt. Die Fehlerbehandlung ist im Beispiel nicht besonders komfortabel ausgelegt, damit der dafür notwendige umfangreiche Code nicht von der eigentlichen Schnittstellennutzung ablenkt.
Das Programm befindet sich in der Datei DeleteRecordsSAM.java:
import java.io.*; import com.fujitsu.ts.jrio.*; /** * This sample program demonstrates the use of the * JRIO interfaces for file handling and random * access to a file. * * This program deletes a sequence of specified records * from a DMS file of type SAM. * * The interesting part of this program is the method * doDeleteRecordsSAM(), all other methods are added * to make it a complete executable program. */ public class DeleteRecordsSAM { /** * The main method, which analyses the program arguments, * calls the work method and provides global error * handling. */ public static void main(String args[]) { String file = null; String first = null; String last = null; int firstNum, lastNum; for (int i = 0; i < args.length; i++) { if (file == null) file = args[i]; else if (first == null) first = args[i]; else if (last == null) last = args[i]; else usage(); } if (file == null || first == null) usage(); try { firstNum = Integer.parseInt(first); if (firstNum < 0) error("Illegal record number " + firstNum); if (last != null) { lastNum = Integer.parseInt(last); if (lastNum < 0 || lastNum < firstNum) error("Illegal record number " + lastNum); } else lastNum = firstNum; doDeleteRecordsSAM(file,firstNum,lastNum); } catch (Exception e) { error(e.toString()); } } /** * Print a usage message and exit with error */ private static void usage() { error("Usage: DeleteRecordsSAM file first [last]"); } /** * Print the given error message and exit */ private static void error(String msg) { System.err.println(msg); System.exit(1); } /** * The work method. * Delete all records between the given record * numbers in a SAM accessible file using * the random access classes of JRIO. * * @param file * The file to modify * @param first * The first record to delete * @param last * The last record to delete */ public static void doDeleteRecordsSAM( String file,int first,int last) throws IOException { Record rec; RecordFile sourceFile; RandomAccessRecordFile update; ArrayOutputRecordStream buffer; Record[] remaining; /** * check file name and create RecordFile object */ sourceFile = new RecordFile(file,"DMS"); /** * check source file existence and write rights */ if (!sourceFile.exists() || !sourceFile.canWrite()) error("Source file " + file + " does not exist" + " or is not writeable"); /** * open file for update */ update = new RandomAccessRecordFile(sourceFile,"SAM", RandomAccessRecordFile.INOUT); /** * check record numbers */ if (first >= update.getRecordCount()) { /** * nothing todo */ update.close(); return; } /** * position to first record after delete area */ update.setCurrentRecordNumber(last + 1); /** * read all remaining records into an array */ buffer = new ArrayOutputRecordStream(); while ((rec = update.read()) != null) buffer.write(rec); remaining = buffer.toRecordArray(); /** * truncate file */ update.setRecordCount(first); /** * append the buffered records to the truncated file */ for (int i = 0; i < remaining.length; i++) update.write(remaining[i]); /** * close the file */ update.close(); } }
Das Programm kann mit dem Java-Compiler javac übersetzt und anschließend zum Ablauf gebracht werden. Es sind dabei keine besonderen Angaben notwendig, um die JRIO-Schnittstellen verfügbar zu haben.
Das zweite Programm gibt einen zufällig ausgewählten „Spruch des Tages“ aus einer Datei (SAM) mit Sprüchen aus. Das Programm erwartet dazu als Parameter den Namen der Datei mit den Sprüchen. Existiert diese noch nicht, wird sie mit einem Grundbestand an Sprüchen neu angelegt.
Das Beispiel ist ebenfalls so angelegt, dass man keine Kenntnisse über die Dateiattribute, wie Satzformat oder Satzlänge, der Datei benötigt. Die Fehlerbehandlung ist im Beispiel nicht besonders komfortabel ausgelegt, damit der dafür notwendige umfangreiche Code nicht von der eigentlichen Schnittstellennutzung ablenkt.
Das Programm befindet sich in der Datei SloganOfTheDay.java:
import com.fujitsu.ts.jrio.*; import java.io.*; import java.util.Random; /** * This example demonstrates a random access to a SAM file. * * A randomly selected record (the slogan of the day) is read * from the file and written to the standard output stream. * If the file with the slogans does not yet exist, it is * created and filled with some standard slogans. * * The interesting part of this program is the method * doSloganOfTheDay(), all other methods are added to make it * a complete executable program. */ public class SloganOfTheDay { /** * The main method, which analyses the program arguments, * calls the work method and provides global error * handling. */ public static void main(String[] args) { if (args.length != 1) usage(); try { doSloganOfTheDay(args[0]); } catch (Exception e) { error(e.toString()); } } /** * Print a usage message and exit with error */ private static void usage() { error("Usage: SloganOfTheDay file"); } /** * Print the given error message and exit */ private static void error(String msg) { System.err.println(msg); System.exit(1); } /** * The work method. * It demonstrates how the JRIO interfaces may be used * for random access to a file. * * @param filename * the file containing the slogans */ public static void doSloganOfTheDay(String filename) throws IOException { /** * the random number generator, used to select the * slogan */ Random generator = new Random(); /** * some slogans to be written to the slogan file * in case it is still empty. */ String[] data = { "Schuster bleib bei deinen Leisten.", "Es fuehren viele Wege nach Rom.", "In ungezaehlten Muehen waechst das Schoene.", "It's better to burn out, than to fade away.", "Make your ideas work!", "Erlaubt ist, was gefaellt.", "Der schoenste Morgen bringt uns das Gestern " + "nicht zurueck.", "Sage nicht immer, was du weisst, aber wisse " + "immer, was du sagst.", "Alles muss man selber machen - sogar das Lachen." }; /** * Definition of the slogan file */ RecordFile rf = new RecordFile(filename, "DMS"); RandomAccessRecordFile slogfile = null; /** * The record object used for accessing * the slogan file */ Record record = null; /** * the number of records in the slogan file */ long numOfRecs = 0; /** * Check if the slogan file is already existing */ if (!rf.exists()) { rf.createNewFile("SAM"); slogfile = new RandomAccessRecordFile(rf, "SAM", RandomAccessRecordFile.OUTIN); for (int i = 0; i < data.length; i++) { record = new Record(data[i].length()); record.setStringData(data[i]); slogfile.write(record); } } else { slogfile = new RandomAccessRecordFile(rf, "SAM", RandomAccessRecordFile.INPUT); } /** * check if there is at least 1 record in the * slogan file * if not, the modulo function would fail */ if ((numOfRecs = slogfile.getRecordCount()) == 0) { slogfile.close(); error("Slogan file is empty!"); } /** * Position to a randomly selected record within * the file. * Thanks to the modulo function (%) we are sure * that the position will always be inside the file */ slogfile.setCurrentRecordNumber( Math.abs(generator.nextInt() % numOfRecs)); /** * read the record and show the slogan */ record = slogfile.read(); System.out.println("Slogan of the day: " + record.getStringData()); /** * close the slogan file */ slogfile.close(); } }
Das Programm kann mit dem Java-Compiler javac übersetzt und anschließend zum Ablauf gebracht werden. Es sind dabei keine besonderen Angaben notwendig, um die JRIO-Schnittstellen verfügbar zu haben.