Java position in file

Java NIO FileChannel

A Java NIO FileChannel is a channel that is connected to a file. Using a file channel you can read data from a file, and write data to a file. The Java NIO FileChannel class is NIO’s an alternative to reading files with the standard Java IO API.

A FileChannel cannot be set into non-blocking mode. It always runs in blocking mode.

Opening a FileChannel

Before you can use a FileChannel you must open it. You cannot open a FileChannel directly. You need to obtain a FileChannel via an InputStream, OutputStream, or a RandomAccessFile. Here is how you open a FileChannel via a RandomAccessFile:

RandomAccessFile aFile = new RandomAccessFile("data/nio-data.txt", "rw"); FileChannel inChannel = aFile.getChannel();

Reading Data from a FileChannel

To read data from a FileChannel you call one of the read() methods. Here is an example:

ByteBuffer buf = ByteBuffer.allocate(48); int bytesRead = inChannel.read(buf);

First a Buffer is allocated. The data read from the FileChannel is read into the Buffer .

Second the FileChannel.read() method is called. This method reads data from the FileChannel into the Buffer . The int returned by the read() method tells how many bytes were written into the Buffer . If -1 is returned, the end-of-file is reached.

Writing Data to a FileChannel

Writing data to a FileChannel is done using the FileChannel.write() method, which takes a Buffer as parameter. Here is an example:

String newData = "New String to write to file. " + System.currentTimeMillis(); ByteBuffer buf = ByteBuffer.allocate(48); buf.clear(); buf.put(newData.getBytes()); buf.flip(); while(buf.hasRemaining()) < channel.write(buf); >

Notice how the FileChannel.write() method is called inside a while-loop. There is no guarantee of how many bytes the write() method writes to the FileChannel. Therefore we repeat the write() call until the Buffer has no further bytes to write.

Читайте также:  Visual studio microsoft csharp

Closing a FileChannel

When you are done using a FileChannel you must close it. Here is how that is done:

FileChannel Position

When reading or writing to a FileChannel you do so at a specific position. You can obtain the current position of the FileChannel object by calling the position() method.

You can also set the position of the FileChannel by calling the position(long pos) method.

long pos channel.position(); channel.position(pos +123);

If you set the position after the end of the file, and try to read from the channel, you will get -1 — the end-of-file marker.

If you set the position after the end of the file, and write to the channel, the file will be expanded to fit the position and written data. This may result in a «file hole», where the physical file on the disk has gaps in the written data.

FileChannel Size

The size() method of the FileChannel object returns the file size of the file the channel is connected to. Here is a simple example:

long fileSize = channel.size();

FileChannel Truncate

You can truncate a file by calling the FileChannel.truncate() method. When you truncate a file, you cut it off at a given length. Here is an example:

This example truncates the file at 1024 bytes in length.

FileChannel Force

The FileChannel.force() method flushes all unwritten data from the channel to the disk. An operating system may cache data in memory for performance reasons, so you are not guaranteed that data written to the channel is actually written to disk, until you call the force() method.

The force() method takes a boolean as parameter, telling whether the file meta data (permission etc.) should be flushed too.

Here is an example which flushes both data and meta data:

Источник

RandomAccessFile

RandomAccessFile encapsulates a random-access file. It is not derived from InputStream or OutputStream.

Instead, it implements the interfaces DataInput and DataOutput, which define the basic I/O methods.

RandomAccessFile implements the Closeable interface.

RandomAccessFile supports positioning requests, you can position the file pointer within the file.

It has these two constructors:

  • RandomAccessFile(File fileObj, String access) throws FileNotFoundException
    fileObj specifies the name of the file to open as a File object.
  • RandomAccessFile(String filename, String access) throws FileNotFoundException
    the name of the file is passed in filename.

access parameter determines what type of file access is permitted.

access Meaning
r the file can be read, but not written.
rw opened in read-write mode.
rws opened for read-write operations and every change (data and metadata) will be immediately written to the physical device.
rwd opened for read-write operations and every change to the file’s data will be immediately written to the physical device.

The method seek( ) sets the current position of the file pointer within the file:

void seek(long newPos) throws IOException 

newPos specifies the new position, in bytes, of the file pointer from the beginning of the file. After a call to seek( ) , the next read or write operation will occur at the new file position.

It includes some additional methods.

One is setLength( ) . It has this signature:

void setLength(long len) throws IOException 

This method sets the length of the invoking file to that specified by len. This method can be used to lengthen or shorten a file. If the file is lengthened, the added portion is undefined.

Create RandomAccessFile in read mode

import java.io.RandomAccessFile; // j ava 2 s . c om public class MainClass < public static void main(String args[]) < try < 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); > > catch (Exception e) < e.printStackTrace(); >> > 

Seek position

import java.io.IOException; import java.io.RandomAccessFile; import java.nio.channels.FileChannel; /* j a va 2 s.c o m*/ public class Main < public static void main(String[] argv) throws IOException < RandomAccessFile randomAccessFile = new RandomAccessFile("test.dat", "r"); randomAccessFile.seek(1000); FileChannel fileChannel = randomAccessFile.getChannel(); // This will print "1000" System.out.println("file pos: " + fileChannel.position()); randomAccessFile.seek(500); // This will print "500" System.out.println("file pos: " + fileChannel.position()); fileChannel.position(200); // This will print "200" System.out.println("file pos: " + randomAccessFile.getFilePointer()); > > 

The file length

import java.io.RandomAccessFile; //from jav a 2s . com public class MainClass < public static void main(String args[]) < try < 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); > > catch (Exception e) < e.printStackTrace(); >> > 

Read into a byte array

import java.io.RandomAccessFile; /* ja v a2s.c o m*/ 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(); > > 

Read a single byte

import java.io.RandomAccessFile; /* j av a 2 s . c o m*/ public class MainClass < public static void main(String args[]) < try < 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); > > catch (Exception e) < e.printStackTrace(); >> > 

Seek position

import java.io.RandomAccessFile; /*ja va 2 s . c o m*/ public class MainClass < public static void main(String args[]) < try < 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); > > catch (Exception e) < e.printStackTrace(); >> > 

Write byte array into RandomAccessFile

import java.io.RandomAccessFile; /*from j a va2 s. c o m*/ public class Main < public static void main(String[] argv) throws Exception < RandomAccessFile file = new RandomAccessFile("scores.html", "rw"); for (int i = 1; i long current = file.getFilePointer(); file.seek(current + 6); file.write("34".getBytes()); for (int i = 1; i current = file.getFilePointer(); file.seek(current + 6); file.write("27".getBytes()); file.close(); > > 

Write String to a RandomAccessFile

import java.io.RandomAccessFile; /*j a v a 2 s . com*/ 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(); > > 

Next chapter.

What you will learn in the next chapter:

Источник

Оцените статью