Java/File Input Output/RandomAccessFile
Версия от 18:01, 31 мая 2010; (обсуждение)
Содержание
- 1 Appending data to existing file
- 2 A RandomAccessFile object that is tied to a file called employee.dat.
- 3 Random IO
- 4 Read from back
- 5 Reading UTF-8 Encoded Data
- 6 Readonly RandomAccessFile
- 7 Reverse a file with RandomAccessFile
- 8 The class demonstrates the use of java.io.RandomAccessFile
- 9 The RandomAccessFile Class
- 10 Translate Charset
- 11 Use RandomAccessFile class
- 12 Use RandomAccessFile to reverse a file
- 13 Use RandomAccessFile to save an object
- 14 Using a Random Access File
- 15 Using the RandomAccessFile class
Appending data to existing file
import java.io.File;
import java.io.RandomAccessFile;
public class Main {
public static void append(String fileName, String text) throws Exception {
File f = new File(fileName);
long fileLength = f.length();
RandomAccessFile raf = new RandomAccessFile(f, "rw");
raf.seek(fileLength);
raf.writeBytes(text);
raf.close();
}
public static void append(String fileName, byte[] bytes) throws Exception {
File f = new File(fileName);
long fileLength = f.length();
RandomAccessFile raf = new RandomAccessFile(f, "rw");
raf.seek(fileLength);
raf.write(bytes);
raf.close();
}
public static void main(String[] args) throws Exception {
append("c:\\tmp.txt", "Appended Data");
append("c:\\tmp.bin", "Appended Data".getBytes());
}
}
A RandomAccessFile object that is tied to a file called employee.dat.
import java.io.IOException;
import java.io.RandomAccessFile;
public class MainClass {
public static void main(String[] args) throws IOException {
RandomAccessFile raf = new RandomAccessFile("employee.dat", "rw");
raf.writeUTF("J");
raf.writeUTF("S");
raf.writeDouble(4.0);
raf.seek(0L);
String fname = raf.readUTF();
String lname = raf.readUTF();
double salary = raf.readDouble();
System.out.println("First name = " + fname);
System.out.println("Last name = " + lname);
System.out.println("Salary = " + salary);
raf.close();
}
}
Random IO
import java.io.IOException;
import java.io.RandomAccessFile;
public class RandomIOApp {
public static void main(String args[]) throws IOException {
RandomAccessFile file = new RandomAccessFile("test.txt", "rw");
file.writeBoolean(true);
file.writeInt(123456);
file.writeChar("j");
file.writeDouble(1234.56);
file.seek(1);
System.out.println(file.readInt());
System.out.println(file.readChar());
System.out.println(file.readDouble());
file.seek(0);
System.out.println(file.readBoolean());
file.close();
}
}
Read from back
import java.io.EOFException;
import java.io.RandomAccessFile;
class Tail {
public static void main(String args[]) throws Exception {
RandomAccessFile raf = new RandomAccessFile(args[0], "r");
long count = 10;
long position = raf.length();
position -= count;
if (position < 0)
position = 0;
raf.seek(position);
while (true) {
try {
byte b = raf.readByte();
System.out.print((char) b);
} catch (EOFException eofe) {
break;
}
}
}
}
Reading UTF-8 Encoded Data
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.InputStreamReader;
public class Main {
public static void main(String[] argv) throws Exception {
BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream("infilename"),
"UTF8"));
String str = in.readLine();
System.out.println(str);
}
}
Readonly RandomAccessFile
/*
* Copyright (c) 1995 - 2008 Sun Microsystems, Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* - Neither the name of Sun Microsystems nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.RandomAccessFile;
import java.util.Vector;
public class ListOfNumbers2 {
private Vector<Integer> victor;
private static final int SIZE = 10;
public ListOfNumbers2() {
victor = new Vector<Integer>(SIZE);
for (int i = 0; i < SIZE; i++)
victor.addElement(new Integer(i));
this.readList("infile.txt");
this.writeList();
}
public void readList(String fileName) {
String line = null;
try {
RandomAccessFile raf = new RandomAccessFile(fileName, "r");
while ((line = raf.readLine()) != null) {
Integer i = new Integer(Integer.parseInt(line));
System.out.println(i);
victor.addElement(i);
}
} catch (FileNotFoundException fnf) {
System.err.println("File: " + fileName + " not found.");
} catch (IOException io) {
System.err.println(io.toString());
}
}
public void writeList() {
PrintWriter out = null;
try {
out = new PrintWriter(new FileWriter("outfile.txt"));
for (int i = 0; i < victor.size(); i++)
out.println("Value at: " + i + " = " + victor.elementAt(i));
} catch (ArrayIndexOutOfBoundsException e) {
System.err.println("Caught ArrayIndexOutOfBoundsException: "
+ e.getMessage());
} catch (IOException e) {
System.err.println("Caught IOException: " + e.getMessage());
} finally {
if (out != null) {
System.out.println("Closing PrintWriter");
out.close();
} else {
System.out.println("PrintWriter not open");
}
}
}
public static void main(String[] args) {
new ListOfNumbers2();
}
}
Reverse a file with RandomAccessFile
import java.io.RandomAccessFile;
class ReverseFile {
public static void main(String args[]) throws Exception {
RandomAccessFile raf = new RandomAccessFile(args[0], "r");
long position = raf.length();
while (position > 0) {
position -= 1;
raf.seek(position);
byte b = raf.readByte();
System.out.print((char) b);
}
}
}
The class demonstrates the use of java.io.RandomAccessFile
/*
* Copyright (c) 2004 David Flanagan. All rights reserved.
* This code is from the book Java Examples in a Nutshell, 3nd Edition.
* It is provided AS-IS, WITHOUT ANY WARRANTY either expressed or implied.
* You may study, use, and modify it for any non-commercial purpose,
* including teaching and use in open-source projects.
* You may distribute it non-commercially as long as you retain this notice.
* For a commercial use license, or to purchase the book,
* please visit http://www.davidflanagan.ru/javaexamples3.
*/
import java.io.IOException;
import java.io.RandomAccessFile;
/**
* This class represents a list of strings saved persistently to a file, along
* with an index that allows random access to any string in the list. The static
* method writeWords() creates such an indexed list in a file. The class
* demostrates the use of java.io.RandomAccessFile
*/
public class WordList {
// This is a simple test method
public static void main(String args[]) throws IOException {
// Write command line arguments to a WordList file named "words.data"
writeWords("words.data", args);
// Now create a WordList based on that file
WordList list = new WordList("words.data");
// And iterate through the elements of the list backward
// This would be very inefficient to with sequential-access streams
for (int i = list.size() - 1; i >= 0; i--)
System.out.println(list.get(i));
// Tell the list we"re done with it.
list.close();
}
// This static method creates a WordList file
public static void writeWords(String filename, String[] words) throws IOException {
// Open the file for read/write access ("rw"). We only need to write,
// but have to request read access as well
RandomAccessFile f = new RandomAccessFile(filename, "rw");
// This array will hold the positions of each word in the file
long wordPositions[] = new long[words.length];
// Reserve space at the start of the file for the wordPositions array
// and the length of that array. 4 bytes for length plus 8 bytes for
// each long value in the array.
f.seek(4L + (8 * words.length));
// Now, loop through the words and write them out to the file,
// recording the start position of each word. Note that the
// text is written in the UTF-8 encoding, which uses 1, 2, or 3 bytes
// per character, so we can"t assume that the string length equals
// the string size on the disk. Also note that the writeUTF() method
// records the length of the string so it can be read by readUTF().
for (int i = 0; i < words.length; i++) {
wordPositions[i] = f.getFilePointer(); // record file position
f.writeUTF(words[i]); // write word
}
// Now go back to the beginning of the file and write the positions
f.seek(0L); // Start at beginning
f.writeInt(wordPositions.length); // Write array length
for (int i = 0; i < wordPositions.length; i++)
// Loop through array
f.writeLong(wordPositions[i]); // Write array element
f.close(); // Close the file when done.
}
// These are the instance fields of the WordList class
RandomAccessFile f; // the file to read words from
long[] positions; // the index that gives the position of each word
// Create a WordList object based on the named file
public WordList(String filename) throws IOException {
// Open the random access file for read-only access
f = new RandomAccessFile(filename, "r");
// Now read the array of file positions from it
int numwords = f.readInt(); // Read array length
positions = new long[numwords]; // Allocate array
for (int i = 0; i < numwords; i++)
// Read array contents
positions[i] = f.readLong();
}
// Call this method when the WordList is no longer needed.
public void close() throws IOException {
if (f != null)
f.close(); // close file
f = null; // remember that it is closed
positions = null;
}
// Return the number of words in the WordList
public int size() {
// Make sure we haven"t closed the file already
if (f == null)
throw new IllegalStateException("already closed");
return positions.length;
}
// Return the string at the specified position in the WordList
// Throws IllegalStateException if already closed, and throws
// ArrayIndexOutOfBounds if i is negative or >= size()
public String get(int i) throws IOException {
// Make sure close() hasn"t already been called.
if (f == null)
throw new IllegalStateException("already closed");
f.seek(positions[i]); // Move to the word position in the file.
return f.readUTF(); // Read and return the string at that position.
}
}
The RandomAccessFile Class
import java.io.RandomAccessFile;
public class Main {
public static void main(String[] argv) throws Exception {
RandomAccessFile file = new RandomAccessFile("scores.html", "rw");
for (int i = 1; i <= 6; i++) {
System.out.println(file.readLine());
}
long current = file.getFilePointer();
file.seek(current + 6);
file.write("34".getBytes());
for (int i = 1; i <= 5; i++) {
System.out.println(file.readLine());
}
current = file.getFilePointer();
file.seek(current + 6);
file.write("27".getBytes());
file.close();
}
}
Translate Charset
import java.io.File;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;
import java.nio.charset.CharsetEncoder;
public class Main {
static public void main(String args[]) throws Exception {
File infile = new File("inFilename");
File outfile = new File("outFilename");
RandomAccessFile inraf = new RandomAccessFile(infile, "r");
RandomAccessFile outraf = new RandomAccessFile(outfile, "rw");
FileChannel finc = inraf.getChannel();
FileChannel foutc = outraf.getChannel();
MappedByteBuffer inmbb = finc.map(FileChannel.MapMode.READ_ONLY, 0, (int) infile.length());
Charset inCharset = Charset.forName("UTF8");
Charset outCharset = Charset.forName("UTF16");
CharsetDecoder inDecoder = inCharset.newDecoder();
CharsetEncoder outEncoder = outCharset.newEncoder();
CharBuffer cb = inDecoder.decode(inmbb);
ByteBuffer outbb = outEncoder.encode(cb);
foutc.write(outbb);
inraf.close();
outraf.close();
}
}
Use RandomAccessFile class
import java.io.RandomAccessFile;
public class Main {
public static void main(String[] args) throws Exception {
RandomAccessFile raf = new RandomAccessFile("books.dat", "rw");
String books[] = new String[5];
books[0] = "A";
books[1] = "B";
books[2] = "C";
books[3] = "D";
books[4] = "E";
for (int i = 0; i < books.length; i++) {
raf.writeUTF(books[i]);
}
raf.seek(raf.length());
raf.writeUTF("Servlet & JSP Programming");
raf.seek(0);
while (raf.getFilePointer() < raf.length()) {
System.out.println(raf.readUTF());
}
}
}
Use RandomAccessFile to reverse a file
import java.io.RandomAccessFile;
public class Main {
public static void main(String[] argv) throws Exception {
RandomAccessFile raf = new RandomAccessFile("a.dat", "rw");
int x, y;
for (long i = 0, j = raf.length() - 1; i < j; i++, j--) {
raf.seek(i);
x = raf.read();
raf.seek(j);
y = raf.read();
raf.seek(j);
raf.write(x);
raf.seek(i);
raf.write(y);
}
raf.close();
}
}
Use RandomAccessFile to save an object
import java.io.IOException;
import java.io.RandomAccessFile;
public class CreateEmployeeFile {
public static void main(String[] args) throws Exception {
String[] fnames = { "A", "B", "C" };
String[] lnames = { "a", "b", "c" };
String[] addresses = { "Box 100", "55 Street", "6 Lane" };
byte[] ages = { 46, 59, 32 };
double[] salaries = { 5.0, 6.0, 3.0 };
RandomAccessFile raf = new RandomAccessFile("employee.dat", "rw");
EmployeeRecord er = new EmployeeRecord();
for (int i = 0; i < fnames.length; i++) {
er.setFirstName(fnames[i]);
er.setLastName(lnames[i]);
er.setAddress(addresses[i]);
er.setAge(ages[i]);
er.setSalary(salaries[i]);
er.write(raf);
}
raf = new RandomAccessFile("employee.dat", "rw");
er = new EmployeeRecord();
int numRecords = (int) raf.length() / er.size();
for (int i = 0; i < numRecords; i++) {
er.read(raf);
System.out.print(er.getFirstName() + " ");
System.out.print(er.getLastName() + " ");
System.out.print(er.getAddress() + " ");
System.out.print(er.getAge() + " ");
System.out.println(er.getSalary());
}
raf.seek(0);
for (int i = 0; i < numRecords; i++) {
er.read(raf);
if (er.getAge() >= 55) {
er.setSalary(0.0);
raf.seek(raf.getFilePointer() - er.size());
er.write(raf);
raf.seek(raf.getFilePointer() - er.size());
er.read(raf);
}
System.out.print(er.getFirstName() + " ");
System.out.print(er.getLastName() + " ");
System.out.print(er.getAddress() + " ");
System.out.print(er.getAge() + " ");
System.out.println(er.getSalary());
}
}
}
class EmployeeRecord {
private String lastName;
private String firstName;
private String address;
private byte age;
private double salary;
void read(RandomAccessFile raf) throws IOException {
char[] temp = new char[15];
for (int i = 0; i < temp.length; i++)
temp[i] = raf.readChar();
lastName = new String(temp);
temp = new char[15];
for (int i = 0; i < temp.length; i++)
temp[i] = raf.readChar();
firstName = new String(temp);
temp = new char[30];
for (int i = 0; i < temp.length; i++)
temp[i] = raf.readChar();
address = new String(temp);
age = raf.readByte();
salary = raf.readDouble();
}
void write(RandomAccessFile raf) throws IOException {
StringBuffer sb;
if (lastName != null)
sb = new StringBuffer(lastName);
else
sb = new StringBuffer();
sb.setLength(15);
raf.writeChars(sb.toString());
if (firstName != null)
sb = new StringBuffer(firstName);
else
sb = new StringBuffer();
sb.setLength(15);
raf.writeChars(sb.toString());
if (address != null)
sb = new StringBuffer(address);
else
sb = new StringBuffer();
sb.setLength(30);
raf.writeChars(sb.toString());
raf.writeByte(age);
raf.writeDouble(salary);
}
void setAge(byte age) {
this.age = age;
}
byte getAge() {
return age;
}
void setAddress(String address) {
this.address = address;
}
String getAddress() {
return address;
}
void setFirstName(String firstName) {
this.firstName = firstName;
}
String getFirstName() {
return firstName;
}
void setLastName(String lastName) {
this.lastName = lastName;
}
String getLastName() {
return lastName;
}
void setSalary(double salary) {
this.salary = salary;
}
double getSalary() {
return salary;
}
int size() {
return 2 * (15 + 15 + 30) + 9;
}
}
Using a Random Access File
import java.io.File;
import java.io.RandomAccessFile;
public class Main {
public static void main(String[] argv) throws Exception {
File f = new File("filename");
RandomAccessFile raf = new RandomAccessFile(f, "rw");
// Read a character
char ch = raf.readChar();
// Seek to end of file
raf.seek(f.length());
// Append to the end
raf.writeChars("aString");
raf.close();
}
}
Using the RandomAccessFile class
import java.io.RandomAccessFile;
public class Main {
public static void main(String[] args) throws Exception {
RandomAccessFile randomAccessFile = null;
String line1 = "line\n";
String line2 = "asdf1234\n";
// read / write permissions
randomAccessFile = new RandomAccessFile("yourFile.dat", "rw");
randomAccessFile.writeBytes(line1);
randomAccessFile.writeBytes(line2);
// Place the file pointer at the end of the first line
randomAccessFile.seek(line1.length());
byte[] buffer = new byte[line2.length()];
randomAccessFile.read(buffer);
System.out.println(new String(buffer));
randomAccessFile.close();
}
}