thx, i am in an evalutation and needed this... you are a life saver !!!!!!
19 May 2010 - 12:33pm by Brian (not verified)
i have a question:
if i have a file tat already has its own content, and i want to write new line at the end line of the file without replace the existing content(i am using BufferedWriter). wat should i do ?
package dummypro;
import java.io.*;
import java.net.*;
import java.nio.*;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.channels.spi.SelectorProvider;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import NioExample.ChangeRequest;
import dummypro.FileServer.FileServerClient;
public class Server1 implements Runnable{
private int port=2020;
private ServerSocket serversocket;
private Socket socket;
private String fileName;
private ServerSocketChannel serversocketchannel;
private SocketChannel socketChannel;
private InetSocketAddress socketAddress;
private Selector selector;
private ByteBuffer readBuffer = ByteBuffer.allocate(8192);
private Map pendingData = new HashMap();
private List pendingChanges = new LinkedList();
public Server1() throws IOException {
serversocketchannel=ServerSocketChannel.open();
serversocketchannel.configureBlocking(false);
this.selector = this.initSelector();
}
private void accept(SelectionKey key) throws IOException {
// For an accept to be pending the channel must be a server socket channel.
ServerSocketChannel serverSocketChannel = (ServerSocketChannel) key.channel();
// Accept the connection and make it non-blocking
SocketChannel socketChannel = serverSocketChannel.accept();
socket = socketChannel.socket();
socketChannel.configureBlocking(false);
// Register the new SocketChannel with our Selector, indicating
// we'd like to be notified when there's data waiting to be read
socketChannel.register(this.selector, SelectionKey.OP_READ);
System.out.println("Acepted client");
}
private Selector initSelector() throws IOException {
// Create a new selector
Selector socketSelector = SelectorProvider.provider().openSelector();
// Create a new non-blocking server socket channel
this.serversocketchannel = ServerSocketChannel.open();
serversocketchannel.configureBlocking(false);
// Bind the server socket to the specified address and port
socketAddress = new InetSocketAddress(this.port);
serversocketchannel.socket().bind(socketAddress);
// Register the server socket channel, indicating an interest in
// accepting new connections
serversocketchannel.register(socketSelector, SelectionKey.OP_ACCEPT);
return socketSelector;
}
private void read(SelectionKey key) throws IOException {
SocketChannel socketChannel = (SocketChannel) key.channel();
// Clear out our read buffer so it's ready for new data
this.readBuffer.clear();
// Attempt to read off the channel
int numRead;
try {
numRead = socketChannel.read(this.readBuffer);
} catch (IOException e) {
// The remote forcibly closed the connection, cancel
// the selection key and close the channel.
key.cancel();
socketChannel.close();
System.out.println("Client losed forcbly");
return;
}
if (numRead == -1) {
// Remote entity shut the socket down cleanly. Do the
// same from our end and cancel the channel.
key.channel().close();
key.cancel();
System.out.println("Client closed cleanly");
return;
}
System.out.println("Proessing for response");
}
private void write(SelectionKey key) throws IOException {
SocketChannel socketChannel = (SocketChannel) key.channel();
synchronized (this.pendingData) {
List queue = (List) this.pendingData.get(socketChannel);
if(queue.isEmpty())
{
System.out.println("Nothing to write");
}
// Write until there's not more data ...
while (!queue.isEmpty())
{
ByteBuffer buf = (ByteBuffer) queue.get(0);
socketChannel.write(buf);
if (buf.remaining() > 0) {
// ... or the socket's buffer fills up
break;
}
queue.remove(0);
}
System.out.println("Write operation completed");
if (queue.isEmpty()) {
// We wrote away all data, so we're no longer interested
// in writing on this socket. Switch back to waiting for
// data.
key.interestOps(SelectionKey.OP_READ);
}
}
}
public void run() {
while (serversocket != null) {
try {
Socket client = serversocket.accept();
System.out.println("client = " + client.getInetAddress());
new Thread( new FileServerClient(client) ).start();
}
catch (IOException e) {
e.printStackTrace();
}
}
while (true) {
try {
// Process any pending changes
synchronized (this.pendingChanges) {
Iterator changes = this.pendingChanges.iterator();
while (changes.hasNext()) {
ChangeRequest change = (ChangeRequest) changes.next();
switch (change.type) {
case ChangeRequest.CHANGEOPS:
SelectionKey key = change.socket.keyFor(this.selector);
key.interestOps(change.ops);
}
}
this.pendingChanges.clear();
}
// Wait for an event one of the registered channels
this.selector.select();
// Iterate over the set of keys for which events are available
Iterator selectedKeys = this.selector.selectedKeys().iterator();
while (selectedKeys.hasNext()) {
SelectionKey key = (SelectionKey) selectedKeys.next();
selectedKeys.remove();
if (!key.isValid()) {
continue;
}
// Check what event is available and deal with it
if (key.isAcceptable()) {
this.accept(key);
} else if (key.isReadable()) {
this.read(key);
} else if (key.isWritable()) {
this.write(key);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
static class FileServerClient implements Runnable {
private Socket socket;
FileServerClient( Socket s) {
socket = s;
}
public void run() {
try {
BufferedOutputStream out = new BufferedOutputStream( socket.getOutputStream() );
FileInputStream fileIn = new FileInputStream("C:/Documents and Settings/Admin/workspace/MyProject/src/dummypro/FileServer.txt");
byte[] buffer = new byte[8192];
int bytesRead =0;
while ((bytesRead = fileIn.read(buffer)) > 0) {
out.write(buffer, 0, bytesRead);
}
out.flush();
out.close();
fileIn.close();
}
catch (IOException e) {
e.printStackTrace();
}
finally {
try {
socket.close();
}
catch (IOException e) {
e.printStackTrace();
}
}
}
}
public static void main(String[] args) {
String userData=null;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter your Data: ");
try {
userData = br.readLine();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("Entered data is "+userData);
try {
BufferedWriter out = new BufferedWriter(new FileWriter("C:/Documents and Settings/Admin/workspace/MyProject/src/dummypro/FileServer.txt"));
out.write(userData);
out.close();
}
catch (IOException e) { }
try {
new Thread(new Server1()).start();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
/* This is a better and simpler approach to read and write file in java*/
import java.io.*;
class Filetransfer
{public static void main (String args[])
{try
{
FileReader fr = new FileReader("testtry.txt"); // use any filename
BufferedReader br = new BufferedReader(fr);
int inputline;
FileWriter fw = new FileWriter("hello.txt"); //use any filename
while((inputline =br.read()) !=-1) // check to see if the file has ended
{
fw.flush();
fw.write(inputline);
}
fr.close();
fw.close();
}catch (IOException e){};
/* Program by Sumish Darak*/
}
}
21 Jul 2010 - 3:02am by Anonymous (not verified)
use BufferedWriter out = new BufferedWriter(new FileWriter(FILE_LOCATION,true));
good
GREAT!!! THANKS!! :)
very good. keep working
Thank you SO much!!!!!!
how will you delete an existing file??
You rock! I want to have your babies
thx, i am in an evalutation and needed this... you are a life saver !!!!!!
i have a question:
if i have a file tat already has its own content, and i want to write new line at the end line of the file without replace the existing content(i am using BufferedWriter). wat should i do ?
use BufferedWriter out = new BufferedWriter(new FileWriter(FILE_LOCATION,true));