Java.nio package
Is there a good tutorial somewhere which explain in depth the new I/O package in JDK 1.4 java.nio?
And there is the JavaWorld article at:
http://www.javaworld.com/javaworld/jw-09-2001/jw-0907-merlin.html
but the example code they give is a little broken, and
the article is also a little confusing. But it can help a little.
I have also started some threads on these forums about the bugs in that article.
Similar Messages
-
Package java.nio package does not exists
I am trying to move some steps in java environment.
I am using a Windows98 O.S.
I downloaded jdk1.3 for Windows from sun site and installed it in c:\jdk1.3.1_02
I have set path variable as .....;c:\jdk1.3.1_02\bin
I am trying to compile a java source including java.nio package.
What I do is:
javac example.java
What I get is:
package java.nio does not exists
I saw a lot of documentation about how to use java.nio but not how to link it.
Any help I appreciate.Package java.nio is introduced with the version 1.4
-
Java.nio package Runtime error java.lang.UnsupportedClassVersionError.
Hi
I am using nio package and create a java program for file locking (FileLocking.java).
Here is the sample
try {
file = new File("C:/acc.txt");
channel = new RandomAccessFile(file, "rw").getChannel();
lock = channel.lock(0, Long.MAX_VALUE, true);
try {
lock = channel.tryLock(0, Long.MAX_VALUE, true);
catch (OverlappingFileLockException e) {
return true;
using wsad 5.1 and jdk1.4 i compiled this program.
While executing i got the following runtime error..
java.lang.UnsupportedClassVersionError: FileLocking (Unsupported major.minor version 48.0)
at java.lang.ClassLoader.defineClass0(Native Method)
at java.lang.ClassLoader.defineClass(ClassLoader.java:703)
at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:133)
at java.net.URLClassLoader.defineClass(URLClassLoader.java:319)
at java.net.URLClassLoader.access$400(URLClassLoader.java:92)
at java.net.URLClassLoader$ClassFinder.run(URLClassLoader.java:677)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:238)
at java.lang.ClassLoader.loadClass(ClassLoader.java:516)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:441)
at java.lang.ClassLoader.loadClass(ClassLoader.java:448)
Exception in thread "main"
Even if i try to recompile it in command prompt and run, i got the same error.
please suggest me how can i overcome this problem.UnsupportedClassVersionError means that you are trying to execute a class for a newer version of the JVM on an older version of the JVM.
Version 48.0 is for Java 1.4, so you have compiled your class with JDK 1.4.
The computer you are trying to run the class on, has an older version of Java than 1.4 - check it!
Try recompiling your source files with the "-target" switch, for example if you're running on Java 1.3, try compiling with:
javac -target 1.3 ... FileLocking.java -
Using ByteBuffer from java.nio package
Hi,
I have a java.nio.ByteBuffer object that is returned from the C++ code, created using NewDirectByteBuffer. I would like to use this ByteBuffer object in my java code to create a WritableRaster object. I would like to avoid an array copy here as the data may be huge.
Could someone please let me know if there is a solution to this?
Thanks in advance for any help.Warning: I know almost nothing about the java.awt.image package - so please take what Im going to suggest as the throw away, off the top of my head random rambling that it is......
Could you implement a custom DataBuffer which sits on top of a NIO ByteBuffer? Already, custom DataBuffers provide access for certain data types (e.g. theres a DataBufferByte, DataBufferDouble which wrap arrays) - so I guess you could write a NIODataBufferByte - or what ever - which sits on top of a ByteBuffer.
Im not sure how this would tie in with the SampleModel though (again, I dont know anything about this area).
Hopefully someone who knows this stuff will come across this thread and actually give you some decent advice :o)
~D -
File Locking using java.nio package
I am trying to lock a file using FileChannel's lock method on a CIFS file system. My application is on windows and the CIFS is accessed using UNC format ( \\1.2.3.4\blah.. ). I get the following error
java.io.IOException: The network request is not supported
at sun.nio.ch.FileChannelImpl.lock0(Native Method)
at sun.nio.ch.FileChannelImpl.lock(FileChannelImpl.java:750)
at java.nio.channels.FileChannel.lock(FileChannel.java:865)
From the same machine using the same UNC formatm, when I lock the file using windows C API, I can successfull lock.
Anyone has any idea why JVM can not lock even using nio package. Shouldnt it use the same ( or similar ) API under the hood as its clear by the package name java.nio
The C program I am using is
#include <io.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/locking.h>
#include <share.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void main( int argc, char **argv )
int fh,numread;
char buffer[40];
char filename[500];
/* Quit if can't open file or system doesn't
* support sharing.
if ( argc > 1 )
strcpy(filename,argv[1]);
else
strcpy(filename,"locking.c");
fh = sopen(filename , O_RDWR, SHDENYNO, //_SH_DENYRW,
SIREAD | SIWRITE );
if( fh == -1 )
exit( 1 );
/* Lock some bytes and read them. Then unlock. */
if( locking( fh, LKNBLCK, 30L ) != -1 )
printf( "No one can change these bytes while I'm reading them\n" );
numread = _read( fh, buffer, 30 );
printf( "%d bytes read: %.30s\n", numread, buffer );
lseek( fh, 0L, SEEK_SET );
printf( "Press a key to unlock the file.....\n" );
getchar();
locking( fh, LKUNLCK, 30L );
printf( "Now I'm done. Do what you will with them\n" );
else
perror( "Locking failed\n" );
_close( fh );
}It uses LockFile and LockFileEx. Please check in the MSDN documentation the peculiarities of such APIs.
JNIEXPORT jint JNICALL
Java_sun_nio_ch_FileChannelImpl_lock0(JNIEnv *env, jobject this, jobject fdo,
jboolean block, jlong pos, jlong size,
jboolean shared)
jint fd = fdval(env, fdo);
HANDLE h = (HANDLE)_get_osfhandle(fd);
DWORD lowPos = (DWORD)pos;
long highPos = (long)(pos >> 32);
DWORD lowNumBytes = (DWORD)size;
DWORD highNumBytes = (DWORD)(size >> 32);
jint result = 0;
if (onNT) {
DWORD flags = 0;
OVERLAPPED o;
o.hEvent = 0;
o.Offset = lowPos;
o.OffsetHigh = highPos;
if (block == JNI_FALSE) {
flags |= LOCKFILE_FAIL_IMMEDIATELY;
if (shared == JNI_FALSE) {
flags |= LOCKFILE_EXCLUSIVE_LOCK;
result = LockFileEx(h, flags, 0, lowNumBytes, highNumBytes, &o);
if (result == 0) {
int error = GetLastError();
if (error != ERROR_LOCK_VIOLATION) {
JNU_ThrowIOExceptionWithLastError(env, "Lock failed");
return sun_nio_ch_FileChannelImpl_NO_LOCK;
if (flags & LOCKFILE_FAIL_IMMEDIATELY) {
return sun_nio_ch_FileChannelImpl_NO_LOCK;
JNU_ThrowIOExceptionWithLastError(env, "Lock failed");
return sun_nio_ch_FileChannelImpl_NO_LOCK;
return sun_nio_ch_FileChannelImpl_LOCKED;
} else {
for(;;) {
if (size > 0x7fffffff) {
size = 0x7fffffff;
lowNumBytes = (DWORD)size;
highNumBytes = 0;
result = LockFile(h, lowPos, highPos, lowNumBytes, highNumBytes);
if (result != 0) {
if (shared == JNI_TRUE) {
return sun_nio_ch_FileChannelImpl_RET_EX_LOCK;
} else {
return sun_nio_ch_FileChannelImpl_LOCKED;
} else {
int error = GetLastError();
if (error != ERROR_LOCK_VIOLATION) {
JNU_ThrowIOExceptionWithLastError(env, "Lock failed");
return sun_nio_ch_FileChannelImpl_NO_LOCK;
if (block == JNI_FALSE) {
return sun_nio_ch_FileChannelImpl_NO_LOCK;
Sleep(100);
return sun_nio_ch_FileChannelImpl_NO_LOCK;
} -
Download java.nio package source code
Where can I find NIO source code? Any Java 5 version would be great.
This code is open source.
thanks!Sun's NIO source can be downloaded from the JDK d/l page.
This IS NOT open source code, you have to agree to the license terms.
If you want open source code, check out the OpenJDK project at java.net -
I'm not sure which forum this should go in so applogies if I got it wrong.
I would like to use the java.nio package from JDK1.4 with the J2ME. Is this possible in any way?
cheers
AndrewI'm not sure which forum this should go in so
applogies if I got it wrong.
I would like to use the java.nio package from JDK1.4
with the J2ME. Is this possible in any way?this topic should be post at
CLDC and MIDP
http://forum.java.sun.com/forum.jsp?forum=76
or
K Virtual Machine (KVM)
http://forum.java.sun.com/forum.jsp?forum=50
CLDC 1.0 and MIDP 1.0 doesn't include java.nio
please go to
http://java.sun.com/j2me/docs/
two documents will be useful
CLDC Specification, V1.0
MIDP 1.0 Specification, Final (JSR 37) -
Java.nio read/write question
Hello,
I just started to learn the java.nio package so I decided to make a simple Echo server. I made a client which reads a line from the keyboard, sends it to the server and the server returns it. It all works except one little detail. Here's little code from the server:
int n = client.read(buffer);
if ( n > 0)
buffer.flip();
client.write(buffer);
Charset charset = Charset.forName("ISO-8859-1");
CharsetDecoder decoder = charset.newDecoder();
charBuffer = decoder.decode(buffer);
System.out.println(charBuffer.toString());
buffer.clear();
}So that works, I send the data and then I receive it back. But only for the client. I also wanted the server to print the line which is the reason for the charset and the decoder. The above code however prints only a blank line. Thus I tried this:
int n = client.read(buffer);
if ( n > 0)
buffer.flip();
Charset charset = Charset.forName("ISO-8859-1");
CharsetDecoder decoder = charset.newDecoder();
charBuffer = decoder.decode(buffer);
System.out.println(charBuffer.toString());
client.write(buffer);
buffer.clear();
}Or in other words I just moved the write() part downwards. So far so good, now the server was actually printing the lines that the client was sending but nothing was sent back to the client.
The question is how to make both, the send back line and the print line on the server side to work as intended. Also a little explanation why the events described above are happening is going to be more than welcome :)
Thanks in advance!Strike notice
A number of the regular posters here are striking in protest at the poor
management of these forums. Although it is our unpaid efforts which make the
forums function, the Sun employees responsible for them seem to regard us as
contemptible. We hope that this strike will enable them to see the value
which we provide to Sun. Apologies to unsuspecting innocents caught up in
the cross-fire. -
Socket disconnection event not being reveived java.nio
Hi All
My question is as below
i am using java.nio package + win 2K + jdk1.4.1_02
I have a Server accepting socket connection and is configured
in Nonblocking mode.
-The server receives (selector) events (accept event)
when a client requests for a connection .
-The server is getting read and write events when
client wants to read and write
-The server gets a read event when the client disconnects
My only problem is that the Server is not getting any events
when the client disconnect due to network break down
for EX when the network connection breaks the client disconnects
but the server selector is not getting any events
I am storing the client Socket objects in a Hash Table and
if i execute the .isConnected() method it returns true
even though the the client is down
The only work around is to try to read and write on the socket
i get an IO exception and am able to make out that the
client is disconnected
But this is not desirable for my client
as client modification to give any kind of echo is not possible and
a read /write event will cause problem.
Can any one tell how to detect client side disconnection
with out Read and Write on the client socket
I get an socket Exception when the socket is in Blocking IO and is blocked on read/ write but I am facing this problem in NonBlockingIO
Regards
Avinashint ct = read.selectNow();
if (ct > 0)
Set readyKeys = read.selectedKeys();
Iterator i = readyKeys.iterator();
while (i.hasNext())
SelectionKey key = (SelectionKey) i.next();
i.remove();
if (key.isReadable())
SelectableChannel nextReady = (SelectableChannel) key.channel();
SocketChannel sc = (SocketChannel) key.channel();
int rd = sc.read(buffer);
// Link is dead
if (rd == -1)
key.cancel();
key.attach(null);
nextReady.close();
continue;
// Process your data
catch (Exception e)
e.printStackTrace(); -
Java NIO and sockets in 1.4.1FCS
Hi,
I have built a client server system using the new 1.4 java.nio packages. In 1.4 everything worked fine, yet in 1.4.1 FCS it definitely does not. The process is as follows.
Everything work in non-blocking mode:
- Server receives connection and accepts it, the new SocketChannel is put in non-blocking mode and registered with the same selector as the server.
- New SocketChannel waits for data from the client so it waits for OP_READ from the selector. All it gets is OP_WRITE, OP_CONNECT. With 1.4 it received OP_READ, OP_WRITE.
I tried adding a call to finishConnect, but that didn't help.
Anyone have any thoughts about this?
Thanks,
Mike.The code in the bug report is incorrect. The key will of course always be writable if you do not write anything to the socket! And since it is writable the readable part of the code will never be executed (its in an else-statement). When you are not interested in the OP_WRITE, change the ops on the selection key.
-
Selecting between java.io and java.nio
Hi,
I'm a bit confused between java.io and java.nio. What sre the major differences between these two?
In areas are these best applicable?The java.nio package improves on the basic Java I/O that was available prior to JDK 1.4.
It is designed to interoperate more natively with the underlying file handles (sockets, open files etc) to achieve better performance.
The improvements include true non-blocking I/O, better buffer management, character-set support, channels (similar to Occam's channels) and selectors, and some other ancillery stuff. Most of these classes are designed to be inherently threadsafe.
There are some examples here:
http://java.sun.com/j2se/1.4.2/docs/guide/nio/example/index.html
However, if you are still a beginner with file or network I/O, its better if you start with the simple I/O first. You'll appreciate the NIO improvements better afterwards. -
Java.nio select() method return 0 in my client application
Hello,
I'm developing a simple chat application who echo messages
But my client application loop because the select() method return 0
This is my code
// SERVER
package test;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Set;
public class Server {
private int port = 5001;
public void work() {
try {
ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
serverSocketChannel.configureBlocking(false);
InetSocketAddress isa = new InetSocketAddress(port);
serverSocketChannel.socket().bind(isa);
Selector selector = Selector.open();
serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
System.out.println("Listing on "+port);
while(selector.select()>0) {
Set keys = selector.selectedKeys();
for(Iterator i = keys.iterator(); i.hasNext();) {
SelectionKey key = (SelectionKey) i.next();
i.remove();
if (key.isAcceptable()) {
ServerSocketChannel keyChannel = (ServerSocketChannel)key.channel();
SocketChannel channel = keyChannel.accept();
channel.configureBlocking(false);
channel.register(selector, SelectionKey.OP_READ );
} else if (key.isReadable()) {
SocketChannel keyChannel = (SocketChannel) key.channel();
String m = Help.read(keyChannel );
Help.write(m.toUpperCase(), keyChannel );
} catch (IOException e) {
e.printStackTrace();
public static void main(String[] args) {
Server s = new Server();
s.work();
// CLIENT
package test;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Set;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
public class Client extends JFrame {
private String host = "localhost";
private int port = 5001;
private SocketChannel socketChannel;
private Selector selector;
public void work() {
try {
socketChannel = SocketChannel.open();
socketChannel.configureBlocking(false);
InetSocketAddress isa = new InetSocketAddress(host, port);
socketChannel.connect(isa);
selector = Selector.open();
socketChannel.register(selector, SelectionKey.OP_CONNECT | SelectionKey.OP_READ );
while(true) {
selector.select();
Set keys = selector.selectedKeys();
for(Iterator i = keys.iterator(); i.hasNext();) {
SelectionKey key = (SelectionKey) i.next();
i.remove();
if (key.isConnectable()) {
SocketChannel keyChannel = (SocketChannel) key.channel();
if (keyChannel.isConnectionPending()) {
System.out.println("Connected "+keyChannel.finishConnect());
} else if (key.isReadable()) {
SocketChannel keyChannel = (SocketChannel) key.channel();
String m = Help.read(keyChannel);
display(m);
} catch (IOException e) {
e.printStackTrace();
private void display(final String m) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
area.append(m+"\n");
textFieed.setText("");
private void sendMessage(final String m) {
Thread t = new Thread(new Runnable() {
public void run() {
try {
Help.write(m, socketChannel);
} catch (IOException e) {
e.printStackTrace();
t.start();
public Client() {
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(1);
textFieed.addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent e) {
if (e.getKeyCode()== KeyEvent.VK_ENTER) {
String m = textFieed.getText();
sendMessage(m);
area.setEditable(false);
getContentPane().add(textFieed, "North");
getContentPane().add(new JScrollPane(area));
setBounds(200, 200, 400, 300);
show();
private String messageToSend;
private JTextArea area = new JTextArea();
JTextField textFieed = new JTextField();
public static void main(String[] args) {
Client s = new Client();
s.work();
// HELPER CLASS
package test;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.channels.SocketChannel;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;
import java.nio.charset.CharsetEncoder;
public class Help {
private static Charset charset = Charset.forName("us-ascii");
private static CharsetEncoder enc = charset.newEncoder();
private static CharsetDecoder dec = charset.newDecoder();
private static void log(String m) {
System.out.println(m);
public static String read(SocketChannel channel) throws IOException {
log("*** start READ");
int n;
ByteBuffer buffer = ByteBuffer.allocate(1024);
while((n = channel.read(buffer)) > 0) {
System.out.println(" adding "+n+" bytes");
log(" BUFFER REMPLI : "+buffer);
buffer.flip();
CharBuffer cb = dec.decode(buffer);
log(" CHARBUFFER : "+cb);
String m = cb.toString();
log(" MESSAGE : "+m);
log("*** end READ");
//buffer.clear();
return m;
public static void write(String m, SocketChannel channel) throws IOException {
log("xxx start WRITE");
CharBuffer cb = CharBuffer.wrap(m);
log(" CHARBUFFER : "+cb);
ByteBuffer buffer = enc.encode(cb);
log(" BUFFER ALLOUE REMPLI : "+buffer);
int n;
while(buffer.hasRemaining()) {
n = channel.write(buffer);
System.out.println(" REMAINING : "+buffer.hasRemaining());
log("xxx end WRITE");Here's the fix for that old problem. Change the work method to do the following
- don't register interest in things that can't happen
- when you connect register based on whether the connection is complete or pending.
- add the OP_READ interest once the connection is complete.
This doesn't fix all the other problems this code will have,
eg.
- what happens if a write is incomplete?
- why does my code loop if I add OP_WRITE interest?
- why does my interestOps or register method block?
For code that answers all those questions see my obese post Taming the NIO Circus
Here's the fixed up Client code
// CLIENT
package test
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Set;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
public class Client extends JFrame {
private String host = "localhost";
private int port = 5001;
private SocketChannel socketChannel;
private Selector selector;
public void work() {
try {
socketChannel = SocketChannel.open();
socketChannel.configureBlocking(false);
InetSocketAddress isa = new InetSocketAddress(host, port);
socketChannel.connect(isa);
selector = Selector.open();
int interest = 0;
if(socketChannel.isConnected())interest = SelectionKey.OP_READ;
else if(socketChannel.isConnectionPending())interest = SelectionKey.OP_CONNECT;
socketChannel.register(selector, interest);
while(true)
int nn = selector.select();
System.out.println("nn="+nn);
Set keys = selector.selectedKeys();
for(Iterator i = keys.iterator(); i.hasNext();)
SelectionKey key = (SelectionKey) i.next();
i.remove();
if (key.isConnectable())
SocketChannel keyChannel = (SocketChannel) key.channel();
System.out.println("Connected "+keyChannel.finishConnect());
key.interestOps(SelectionKey.OP_READ);
if (key.isReadable())
SocketChannel keyChannel = (SocketChannel) key.channel();
String m = Help.read(keyChannel);
display(m);
} catch (IOException e) {
e.printStackTrace();
private void display(final String m) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
area.append(m+"\n");
textFieed.setText("");
private void sendMessage(final String m) {
Thread t = new Thread(new Runnable() {
public void run() {
try {
Help.write(m, socketChannel);
} catch (IOException e) {
e.printStackTrace();
t.start();
public Client() {
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(1);
textFieed.addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent e) {
if (e.getKeyCode()== KeyEvent.VK_ENTER) {
String m = textFieed.getText();
sendMessage(m);
area.setEditable(false);
getContentPane().add(textFieed, "North");
getContentPane().add(new JScrollPane(area));
setBounds(200, 200, 400, 300);
show();
private String messageToSend;
private JTextArea area = new JTextArea();
JTextField textFieed = new JTextField();
public static void main(String[] args) {
Client s = new Client();
s.work(); -
Java.nio.channels.FileChannel jar file
Hi
I have used java.nio.channels.FileChannel package in my program.
where can I get the jar file which has the above package?
Thanxi give here sample code.. use this it will work fine..
import java.nio.*;
import java.nio.channels.*;
import java.io.*;
public class copyImage
public static void main(String [] args) throws IOException
try {
// Create channel on the source
FileChannel srcChannel = new FileInputStream("dragonfly.jpg").getChannel();
FileChannel dstChannel =new FileOutputStream("1.jpg").getChannel();
// Copy file contents from source to destination
dstChannel.transferFrom(srcChannel, 0, srcChannel.size());
// Close the channels
srcChannel.close();
dstChannel.close();
} catch (IOException e) {
} -
Java.nio.channels.Pipe?
Someone explain what java.nio.channels.Pipe should be uses for, and how to use it?
You can use this class to transfer the content of a channel from one thread to another thread.
The writing thread blocks when the pipe is full.
package com.desoft.pipetest;
import java.io.*;
import java.nio.*;
import java.nio.channels.*;
public class PipeTest {
public static void main (String args[])
try
FileInputStream fis = new FileInputStream(args[0]);
FileChannel fc = fis.getChannel();
Pipe p = Pipe.open();
PipeReader pr = new PipeReader( p );
Thread t = new Thread( pr );
t.start();
fc.transferTo(0, fc.size(), p.sink() );
catch( IOException ioe )
ioe.printStackTrace();
* Read from a Pipe and write Content to System.out
static class PipeReader implements Runnable
Pipe p;
public PipeReader( Pipe p )
this.p = p;
public void run()
try
ByteBuffer buffer = ByteBuffer.allocate( 10 );
int len = 0;
while( (len=p.source().read( buffer )) > 0 )
buffer.rewind();
for( int i = 0; i < len; i++ )
System.out.print( (char)buffer.get());
buffer.rewind();
catch( IOException ioe )
ioe.printStackTrace(); -
Performance of java nio with dd in linux.
Hi
I ran this code in java to dump 0s in a file of size 1gb and tried the same with dd in linux.
Java code : I use a preinitialized array (the data) and fill a mappedbytebuffer with it.
package filePersistence.test;
import java.io.File;
import java.io.RandomAccessFile;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
public class TimeLineTest {
private static final int BYTE_LENGTH = 1000;
//this is the input
static byte[] b = new byte[BYTE_LENGTH];
public static void main(String[] arg) throws Exception
//initializing the input
for (int i=0;i<BYTE_LENGTH;i++)
b[i] = 0;
File file = new File(arg[0]);
RandomAccessFile raFile = new RandomAccessFile(file,"rw");
FileChannel fChannel = raFile.getChannel();
int loopCount = 1000000;
MappedByteBuffer mbuffer = fChannel.map( FileChannel.MapMode.READ_WRITE ,0,loopCount * BYTE_LENGTH);
//System.out.println(" going to fill in a file" + file.getName());
long k = 0;
long startTime = System.currentTimeMillis();
for (int i=0;i<loopCount;i++)
//populate the mapped buffer
mbuffer.put(b);
//persist into the file
mbuffer.force();
long endTime = System.currentTimeMillis();
System.out.println(" file filled size1 "+file.length());
System.out.println(" time " + (endTime - startTime));
On a linux machine this takes around 7 secs while dd used as
"dd if=/dev/zero of=mytestfile.out bs=1000 count=1000000"
1000000+0 records in
1000000+0 records out
1000000000 bytes (1.0 GB) copied, 4.618 seconds, 217 MB/s
4.6 and 7 differ quite a lot. Is there a way the java code can be improved to match dd ?(-sever does not help)
Thanks
SumantaHi
Can this be called a dd equivalent code ?
package filePersistence.test;
import java.io.File;
import java.io.FileOutputStream;
import java.io.RandomAccessFile;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
public class TimeLineTest {
private static final int BYTE_LENGTH = 1000;
//this is the input
static byte[] b = new byte[BYTE_LENGTH];
public static void main(String[] arg) throws Exception
//initializing the input
for (int i=0;i<BYTE_LENGTH;i++)
b[i] = 0;
String srcFile = arg[0] + "_src";
FileOutputStream fos = new FileOutputStream(srcFile);
fos.write(b);
fos.getFD().sync();
fos.flush();
fos.close();
RandomAccessFile srcraFile = new RandomAccessFile(srcFile,"rw");
FileChannel srcChannel = srcraFile.getChannel();
File file = new File(arg[0]);
RandomAccessFile raFile = new RandomAccessFile(file,"rw");
FileChannel raChannel = raFile.getChannel();
int loopCount = 1000000;
//MappedByteBuffer mbuffer = fChannel.map( FileChannel.MapMode.READ_WRITE ,0,loopCount * BYTE_LENGTH);
//System.out.println(" going to fill in a file" + file.getName());
long startTime = System.currentTimeMillis();
for (int i=0,position=0;i<loopCount;i++,position+=BYTE_LENGTH)
//populate the mapped buffer
//mbuffer.put(b);
raChannel.position(position);
srcChannel.transferTo(0, BYTE_LENGTH, raChannel);
//persist into the file
//mbuffer.force();
raFile.getFD().sync();
raChannel.close();
raFile.close();
long endTime = System.currentTimeMillis();
System.out.println(" file filled size1 "+file.length());
System.out.println(" time " + (endTime - startTime));
}
Maybe you are looking for
-
Wireless connection problems with iTunes
After installing iTunes for my PC(using Windows Vista if that matters). Directly after installing iTunes my wireless connection works. Once I start importing my music into iTunes I lose my wireless connection. I can still see the wireless networks bu
-
Need help installing keep getting error message when i install program
i download the beta version on my android epic phone by sprint and when i go to install the program it shows a screen installing then an error message pops up almost immediately and say that application was not installed how do i fix this i have trie
-
How can I transfer presets that I create between accounts
Hello, I created some presets in Pr Pro while logged in under my Admin account. The presets showed up when I created a new project while in the Admin account. But when I switched over to my other account the presets did not show up. I would like t
-
I just bought an iPod shuffle 1gb and i'm having the following problem. I have a huge mp3 collection divided into different cds. The thing is that everytime i send mp3s from a CD to the iPod and reconnect the pod (withouth having the CD in the CD-ROM
-
CSA* BDoc Queues that will not dequeue
Hello, I am trying to solve a problem with queues that will NOT dequeue automatically the BDocs in the Q&A environment (dev is OK). This is the context: NW2004s, Q&A CRM 5.0 BDoc processing When I create a new BP, a BDoc is created. If I go to the SW