NIO write flush problem?

Hello there,
I've got a odd problem here, and it's going to be hard to explain so please excuse me if I haven't explained correctly. I'm writing a Java application, which uses nio, with non blocking sockets, to handle its networking. I presumably have a problem with writing data. Quick recap of the problem is that for some reason, data gets concatenated to each other and then sent. So for example, let's say I'd want to send 'hello' and 'there'. What my application sometimes does, is sending 'hellothere' instead of sending 'hello', and then, in a new packet, 'there'.
What now happens on the server side is that it receives 'hellothere' and doesn't know what do with it, while it would have worked fine if they were separated.
This is a snippet coming from the server. This is always running on background (in a thread), in a loop.
synchronized (m_ChangeRequests)
                    Iterator changes = m_ChangeRequests.iterator();
                    while (changes.hasNext())
                        ChangeRequest change = (ChangeRequest)changes.next();
                        switch (change.getType())
                            case ChangeRequest.CHANGEOPS:
                                SelectionKey key = change.getSocket().keyFor(m_Selector);
                                try
                                    key.interestOps(change.getOps());
                                catch (NullPointerException e)
                                    disconnectClient(getClientWithChannel(change.getSocket()));
                    m_ChangeRequests.clear();
// Waiting for events
                m_Selector.select(1000);
                // Get keys
                Set keys = m_Selector.selectedKeys();
                Iterator i = keys.iterator();
                // For each keys...
                while(i.hasNext())
                    SelectionKey key = (SelectionKey) i.next();
                    // Remove the current key
                    i.remove();
                    // if isAccetable = true
                    // then a client required a connection
                    if (!key.isValid())
                        continue;
                    if (key.isAcceptable())
                        accept(key);
                    else if (key.isReadable())
                        read(key);
                    else if (key.isWritable())
                        write(key);
                }Now, I suppose the important method here is write().
private void write(SelectionKey key)
        SocketChannel socketChannel = (SocketChannel)key.channel();
        synchronized (m_PendingData)
            List queue = (List)m_PendingData.get(socketChannel);
            while (!queue.isEmpty())
                try
                    ByteBuffer buf = (ByteBuffer)queue.get(0);
                    System.out.println(socketChannel.write(buf));
                    if (buf.hasRemaining())
                        continue;
                    queue.remove(0);
                catch (IOException ioe)
                    ioe.printStackTrace();
            if (queue.isEmpty())
                key.interestOps(SelectionKey.OP_READ);
              As you can see I'm using a variable m_PendingData there, which is simply a HashMap. There is another important method, which is the send method.
public void send(SocketChannel socket, byte[] data)
        synchronized (m_ChangeRequests)
            m_ChangeRequests.add(new ChangeRequest(socket, ChangeRequest.CHANGEOPS, SelectionKey.OP_WRITE));
            synchronized (m_PendingData)
                List queue = (List)m_PendingData.get(socket);
                if (queue == null)
                    queue = new ArrayList();
                    m_PendingData.put(socket, queue);
                queue.add(ByteBuffer.wrap(data));
        m_Selector.wakeup();
    }You might have noticed the m_ChangeRequests variable. Please see the first code snippet for what it does. It's a LinkedList.
Sorry if I have not explained it clear enough. I suppose this problem could also be in the read method, I assume it is in the write method though.
Thanks,
Lars

Basically you can't think of reading and writing to/from sockets in terms of packets - you write some bytes to the socket at one end, and read some bytes at the other. This is true for both blocking and non blocking sockets.
If you want your bytes to be split into meaningful packets, then you have to encode the packet format yourself. A really simple way to do that is to start each message with a fixed number of bytes that contain the number of data bytes in the packet - from your example this would give:
5 hello 5 there
On the reading end, your server will then be able to read the initial byte count of each packet and know how much data is expected.

Similar Messages

  • Nio write problem: server data sent isn't fully read by client

    Hi everyone,
    still writing away with my nio server and once again have run into
    some problems. Essentially my main problem is that when the server
    writes to the client, the write appears to output all the bytes in the
    write operation, but the client never accepts them all, even if a
    buffer has been manually allocated to the correct size of the data.
    As background my server will accept connections. When a connection
    is established I register OP_READ on the key. When a OP_READ trigger
    occurs the server accepts the clients request, processes it, then
    attaches the output to the SelectionKey as a ByteBuffer that has
    already been encoded. At this point I then register OP_WRITE on that
    SelectionKey (as a side note i'm running this server on XP and had
    read that registering OP_READ and OP_WRITE on the same selector was
    bad, but then it looked like there was a work around to this) and wait
    for an OP_WRITE trigger.
    When an OP_WRITE occurs on that key I run a new method (with heavy
    influences from the thread: http://forum.java.sun.com/thread.jsp?forum=11&thread=530825 and the taming the nio circus thread) which will grab the attachment and attempt to send it. The code has been written that IF the send cannot complete it should re-attach the remaining bytebuffer to the key and wait for another OP_WRITE to occur so it can send the remainder.
    The problem is that whenever I write (and for this test the amount im writing is approx 10100 bytes) the server appears to send it all (by checking the int returned from socketchannel.write()), but at the client end it never reads all the data that is sent.
    If i'm using a blocking socket client, then I get a java.net.SocketException: Connection Reset exception, whilst if i'm using a non-blocking client, I get no exception, just not the whole amount of data, even when i've statically allocated a receiving bytebuffer that is big enough.
    The following code is a class that is used to do the writing from the server:
       /* code for nio write model referenced from:
         * http://forum.java.sun.com/thread.jsp?forum=11&thread=530825
        class NIOWriteHandler {
            private ByteBuffer sendBuffer;
            private SelectionKey localSelectionKey;
            NIOWriteHandler(SelectionKey currentKey) {
                localSelectionKey = currentKey;
            public void doWrite() {
                localSelectionKey.interestOps(SelectionKey.OP_READ);  //deselect write,
                sendBuffer = (ByteBuffer)localSelectionKey.attachment();
                // perform the writing
                SocketChannel writingChannel = (SocketChannel)localSelectionKey.channel();
                if (writingChannel.isOpen()) {
                    int len = 0;
                    if (sendBuffer.hasRemaining()) {
                        try {
                            System.out.println("Sending chunks o data");
                            len = writingChannel.write(sendBuffer);
                            System.out.println("value of len: " + len);
                        } catch (IOException ioe) {
                            ioe.printStackTrace();
                            // call close method
                            System.out.println("CLOSE INVOKED at POINT 8");
                            closeComplete(localSelectionKey);
                    System.out.println("Second IF coming...");
                    if (sendBuffer.hasRemaining()) {
                        // if we get here then the previous write did not fully
                        // complete, so need to save data etc
                        System.out.println("Couldn't send all data this time...");
                        localSelectionKey.interestOps(SelectionKey.OP_WRITE|SelectionKey.OP_READ);
                        localSelectionKey.attach(sendBuffer);
                    } else {
                        sendBuffer = null;
                        closeComplete(localSelectionKey);
                // write complete at this stage
        }This is the basic block client that is incredibly dumb:
    import java.net.*;
    import java.util.*;
    import java.io.*;
    import java.nio.charset.*;
    import java.nio.channels.*;
    import java.nio.*;
    import java.nio.ByteBuffer;
    public class ServerTest {
        /* args 0 - the IP of the machine to connect to
           args 1 - the port number
           Simple client that connects to a specified IP & port, takes a line
           of input via stdin, sends that to the connected machine and prints
           out the response.
           Error handling and such isn't accounted for.
       public static void main (String args[]) throws Exception{
            Socket socket = new Socket(args[0], Integer.parseInt(args[1]));
            BufferedReader buffRead = new
                BufferedReader(new InputStreamReader((socket.getInputStream())));
            PrintStream ps =
                new PrintStream(socket.getOutputStream());
            Charset charset = Charset.forName("ISO-8859-1");
            BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in));
            System.out.println("[CLIENT]Data to send: ");
            String data = stdin.readLine();
            ps.println(data);
            String returned = buffRead.readLine();
            while (returned != null) {
                System.out.println(returned);
                returned = buffRead.readLine();
            System.out.println("[CLIENT]End server response");
            buffRead.close();
            ps.close();
            socket.close();
    }And here is the non-blocking basic client (which dosn't actually close at the moment):
    import java.net.*;
    import java.util.*;
    import java.io.*;
    import java.nio.charset.*;
    import java.nio.channels.*;
    import java.nio.*;
    public class ServerTestNonBlock {
        /* args 0 - the IP of the machine to connect to
           args 1 - the port number
           Simple client that connects to a specified IP & port, takes a line
           of input via stdin, sends that to the connected machine and prints
           out the response.
           Error handling and such isn't accounted for.
       public static void main (String args[]) throws Exception{
            InetSocketAddress addr = new InetSocketAddress
                (args[0], Integer.parseInt(args[1]));
            SocketChannel sc = SocketChannel.open();
            sc.configureBlocking(false);
            Selector selector = Selector.open();
            System.out.println("Starting connection...");
            sc.connect(addr);
            while(!sc.finishConnect()) {
               System.out.println("1,2,3,4 I will keep on counting...");
            System.out.println("Connection established..");       
            Charset charset = Charset.forName("ISO-8859-1");
            CharsetEncoder encoder = charset.newEncoder();
            sc.register(selector, SelectionKey.OP_READ | SelectionKey.OP_WRITE);
            while (true) {
               int n = selector.select();
               if (n==0) {
                  continue;
               Set keys = selector.selectedKeys();
               Iterator it = keys.iterator();
               while (it.hasNext()) {
                  SelectionKey selKey = (SelectionKey)it.next();
                  if (selKey.isReadable()) {
                     // time to setup read
                     ByteBuffer incomingData =
                        ByteBuffer.allocateDirect(102000);
                     incomingData.clear();
                     int count;
                     while ((count = sc.read(incomingData)) > 0) {
                        System.out.println("Value of count: " + count);
                        // reading the data
                     System.out.println("Count value: " + count);       
                     int pos = incomingData.position();
                     incomingData.flip();
                     CharBuffer content = charset.decode(incomingData);
                     String inData = content.toString();
                     System.out.println(inData.trim());
                     System.out.println("[CLIENT]End server response");
                     System.out.println("Count value: " + count);       
                     System.out.println("Position value: " + pos);       
                     //sc.close();
                     //break;
                  if (selKey.isWritable()) {
                     BufferedReader stdin = new BufferedReader
                       (new InputStreamReader(System.in));
                     System.out.println("[CLIENT]Data to send: ");
                     String data = stdin.readLine();
                     ByteBuffer byteBufferOut = encoder.encode
                        (CharBuffer.wrap(data));
                     int length = sc.write(byteBufferOut);
                     System.out.println("Wrote: " + length + " bytes.");
                     selKey.interestOps(SelectionKey.OP_READ);
    }I'm kinda stuck at the moment and am making change for the sake of change without getting a good grasp of what is going on. If anyone can provide any help that'd be fantastic. If in the mean time I figgure something out i'll post a response.
    If you've gotten this far thanks a bunch for reading :)
    Cheers,
    Pete

    Hi Meesum,
    thanks for the reply :)
    I'm not convinced this is the error - as i've got two clients listed there, and the odd behaviour from both is that neither is getting through to the last of the data that is sent.
    If the null were the problem (which is only checked for in the basic dumb blocking client) i'd be expecting some sort of infinite loop or wait for more data from the server, not an abnormal termination (ala connection reset) from the server. I'll give it a shot anyhow, but I know that under a blocking write operation that that code worked fine.
    Thanks again though for the post, has got some of my cogs slowly turning :)
    Cheers,
    Pete

  • In AIR 3.x, a socket write()+flush() on a client will hang app if peer adverts TCP ZERO WINDOW

    In AIR 3.x, a socket write() + flush() on a client will hang (and freeze the entire app) if the socket peer advertises a ZERO TCP Window, i.e. no space available in peer receiver's socket buffer.
    AIR on Windows insists that the developer flush() the socket in order to write (any data at all).  When the peer (receiver) advertises a 0 byte tcp window, the client flush() call can sometimes take 10 seconds (i.e. 10000 milliseconds), whereas normally it should take 10 to 50 milliseconds.
    Additionally, AIR stayed in hung position.  Since the socket had TCP KEEPALIVE option enabled (at the server), the socket stayed open.  I let it stay hung overnight.  The next day when I rebooted the server, the socket got closed and finally the AIR program "RETURNED FROM the sock.flush()" call.  A timestamp before and after the call to flush() showed that the flush() call was in hung state for 56472475 milliseconds, i.e. 15.7 hours!  After it returned from the flush() call the AIR app was responsive and seemed to work properly.  Thus proving that it was indeed stuck (or blocked) on the flush() call for 15 hours trying to drain the data to a socket with zero tcp window condition.
    A tcp zero window condition on 1 socket hanging an entire app sounds concerning.
    Solution Suggestions:
    (1) What is needed is for the OutputProgress event to include a field for 'bytes that can be written safely without blocking on the socket', i.e. 'space available in underlying platform socket buffer' which would account for the socket send buffer size.
    (2) An alternative solution would be for AIR to provide a write-timeout setsockopt (or a writeTimeout() method on the socket), and return flush with an error (or EWOULDBLOCK), and call the OUTPUTPROG event only when there is enough space available.
    If there are any other workarounds, please let me know.
    Thank you.

    Question:  Does Adobe AIR expose the getsockopt() and setsockopt() calls on a socket?  It would be useful to apps to tune the io buffer sizes.
    Additional Details:
    RTT = 100+ milliseconds
    TCP Window Scaling enabled
    Secure Socket
    Hard to reproduce with plain TCP socket, but occurs without fail with SecureSocket.  Not knowing the underlying code base, am wondering if it is because the SSL encryption overhead (bytes) throws off the buffer available size compution in secure_sock.flush() .
    Thanks.

  • Write access problem with external Storage Device Connected to macbook

    Hi All,
    I have write access problem ( gives only read-access, but no write access) with an external HDD device (NTFS formatted ) connected to my macbook.
    Could anyone suggest me a file system ( apart from FAT32) which is compatiable with both Mac OS as well windows ;also this file system should allow me to create partitions of size more than 100 GB
    (My external storade devcie capacity is 500 GB )
    Thanks
    Nelson

    Hi Nelson,
    simply said there is no such file system.
    Regardless what you choose, only FAT32 is fully read-/writeable from both Mac OSX and Windows.
    Third-Party helper for access to certain file systems are:
    MacDrive (for Windows using HFS+, the OSX file system)
    MacFuse with 3G (for fully usage of NTFS in OSX)
    Paragon NTFS for OSX (also for fully usage of NTFS in OSX)
    Only MacFuse is freeware, the other two are Commercial apps.
    And just in case you are thinking of any Linux file system, like Ext3 or ReiserFS, you will at least need driver for Windows if not also for OSX (not sure about that).
    Regards
    Stefan

  • Writer.flush() : is it always needed?

    Hi everybody,
    This is just a general IO question. When I learned Java, I was taught that when you use a FileWriter or BufferedWriter, it's good practice to call writer.flush() after writing any line. Is this true, or is that a waste of time? I'm just curious.
    Thanks,
    Jezzica85

    Hi everybody,
    This is just a general IO question. When I learned
    Java, I was taught that when you use a FileWriter or
    BufferedWriter, it's good practice to call
    writer.flush() after writing any line. Is this true,
    or is that a waste of time? I'm just curious.
    Thanks,
    Jezzica85Flush will commit the data you have written to your disk. Sort of like close() but leaves the stream open.

  • Problem with Writer.flush() appending extra character

    I have written a simple file copy that does the following:
         public static void copy(File source, File dest) throws IOException
              FileReader fr = new FileReader(source);
              FileWriter fw = new FileWriter(dest);
              try
                   char[] ch = new char[(int)source.length()];
                   fr.read(ch);
                   fw.write(ch);
              finally
                   fr.close();
                   fw.close();
    It works fine, and has done for some time.
    For some reason, in a recent data collection, I have 3 files out of about a hundred, where the following behaviour occurs.
    The char array is written to the file fine. For some reason when fw.flush() is called (i have tested this and confirmed that it is the call to flush() that is causing it) it appends a char to the end of the file with a value of -1.
    This is causing merry havoc with my XML parser.
    Can anybody tell me how to stop Writer from adding a -1 to my file?
    This is on java 1.4.2 currently.

                   char[] ch = new char[(int)source.length()];File.length() returns the number of bytes in the file.
    However, you're loading that file via a Reader, which converts those bytes into characters using some encoding method. Depending on the encoding, the number of characters produced may be completely different from the number of bytes read. It's also possible that the bytes read are not valid with the encoding.
    If you're just copying files, use FileInputStream and FileOutputStream. Better, download the Jakarta Commons IO library, and use their already-tested methods.
    If you're working with a JAXP XML parser (ie, what comes with JDK 1.4 and above), create your InputSource from a FileInputStream. That will let the XML parser use the encoding specified in the file, ignoring whatever your JRE's default encoding is.
    If you're planning to work with the raw text, then you're going to have to learn about character encodings. I don't have a tutorial link handy, so either Google for one or start with the documentation for java.nio.charset.Charset.

  • NIO write problem

    Hello,
    I am seeing a weird behavior when performing a write operation on a non-blocking socket channel. The write call completes normally for several write invocations, however when the total number of bytes written exceeds 8K the sending of data grinds to a halt. All subsequent writes take an excessive amount of time to actually send (10+ secs). It seems to send only a few bytes at time once the 8K threshold is reached. Since it is non-blocking the write call returns immediately, however looking at the actual transmission that occurs, it gets transmitted extremely slow. The far-end is consuming all bytes as they come in, so it should not be backing up on the socket, but it seems that it is having trouble sending the data.
    Any thoughts or help would be greatly appreciated.
    Thanks!

    I'm also seeing something similar. Did you ever find a resolution to this issue?

  • Read file with nio and flush with servlet

    Can I read file, by using java.nio (for example by FileInputStream.getChannel()) and then flush the file content thru the servlet?
    I kwow about reading without java.nio, get a byte array and then flush it by httpservletresponse writer or outputstream, but I wish to know if it is possibile with java.nio reading.
    thanks

    I'm doing it only for file reading..
    protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
            response.setContentType("text/html;charset=UTF-8");
            PrintWriter out = response.getWriter();    
            FileInputStream fis = null;                               
            try
                String path = "/var/hello.txt";
                fis = new FileInputStream(path);       
                FileChannel channel =  fis.getChannel();
                ByteBuffer bb = ByteBuffer.allocate((int) channel.size());
                channel.read(bb);
                byte[] data2 = bb.array();
                channel.close();
                out.write(new String(data2));
            } catch (FileNotFoundException ex)
                ex.printStackTrace();
            } finally
                try
                    fis.close();
                } catch (IOException ex)
    ex.printStackTrace();
                out.close();
        }

  • Read and write file problem

    hello
    I have web application and I try using servlet to upload an image
    upload proccess works fine
    example
    1. I upload the the file C:\images\books\mybook.gif into
    temp folder
    2. other actions
    3. I want to write the fole mybook.gif into othet folder
    this process oerks fine on my home pc
    but I becom an ecxeption by webprovider
    /home/mydomain/public_html/projects/tempData/C:\images\books\mybook.gif(No such file or directory)what shoud be the problem and how to solve this issue
    thanks

    here is the code of the uploadservlet
    public void doPost(HttpServletRequest request, HttpServletResponse response)
                   throws ServletException, IOException
        PrintWriter out = null;
        String tempUploadDir = request.getSession().getServletContext().getRealPath("/")+"MyTemp"+File.separator;
         try
              out = response.getWriter();
             response.setContentType("text/html");
             MultipartRequest parser = new ServletMultipartRequest(request,
                                                                               MultipartRequest.MAX_READ_BYTES,
                                                                               MultipartRequest.IGNORE_FILES_IF_MAX_BYES_EXCEEDED,
                                                                               null);
                 Enumeration files= parser.getFileParameterNames();
                      while(files.hasMoreElements()){
                                boolean sizeOK    = true;         
                                String name       = (String)files.nextElement();
                                String filename   = parser. getBaseFilename(name);
                              InputStream ins   = parser.getFileContents(name);
                              if((parser.getFileSize(name) / 1024) > AppConstants.MAX_READ_BYTES){sizeOK = false;}
                         if(sizeOK){
                              if (ins!=null)
                                      BufferedInputStream input = new BufferedInputStream(ins);
                                   FileOutputStream outfile = new FileOutputStream(new File("MyTemp",filename));
                                             int read;
                                             byte[] buffer = new byte[4096];
                                             while ((read=input.read(buffer))!=-1){
                                                        outfile.write(buffer, 0, read);
                                             outfile.close();
                                             input.close();
             }// end out while
         }catch (Exception e) {  out.flush(); }
    what is to change here thanks

  • Read(Load)/Write(Save) Problem

    I have a form that is filled out by people and I want to save the information in a text file. I have done that well at least I think with the Save code. My problem is when I go to load the text file (.CMM file for my program), nothing happens but it does print out my File Loaded message in the console. Any idea where I am missing something? The getter and setter methods all seem to be correct...
    private void SavePrefs() {
              File SavePrefs;
              // get filename:
              fc.setDialogTitle("Select Filename For Site Data");
              int result = fc.showSaveDialog(f);
              if (result == JOptionPane.OK_OPTION) {
                   SavePrefs = fc.getSelectedFile();
                   // default file extension ".CMM"
                   if (!SavePrefs.getName().endsWith(".CMM")) {
                        // filename does not meet requirements:
                        System.out.println("NO CMIMS in filename");
                        SavePrefs = new File(SavePrefs.getAbsolutePath() + ".CMM");
                   // continue with save code:
                   System.out.println("File Selected:" + SavePrefs.toString());
                   //Creates a .cmm file with all the data in it.
                   FileOutputStream saveData;
                   PrintStream data;
                   try {
                        saveData = new FileOutputStream(SavePrefs.toString());
                        data= new PrintStream(saveData);
                        data.println("CLOSE YEAR="+_SitePropPanel.getCloseYear());
                        data.println("OPEN YEAH="+_SitePropPanel.getOpenYear());
                        //data.println("COL RATE = "+_SitePropPanel.getCollectionRate());
                        data.println("GAS RECOV STATE="+_SitePropPanel.getGasRecoveryState());
                        data.println("SITE CLOSED="+_SitePropPanel.getLandfillClosed());
                        data.flush();
                        data.close();
                        saveData.flush();
                        saveData.close();
                   } catch (FileNotFoundException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                   } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                   System.out.println("File Saved");
              // not OK selected (cancel or.?)
         private void LoadPrefs() {
              File loadPrefs;
              // get filename:
              fc.setDialogTitle("Select Filename For Site Data");
              int result = fc.showOpenDialog(f);
              if (result == JOptionPane.OK_OPTION) {
                   loadPrefs = fc.getSelectedFile();
                   // default file extension ".CMM"
                   if (!loadPrefs.getName().endsWith(".CMM")) {
                        // filename does not meet requirements:
                        System.out.println("NO CMIMS in filename");
                   // continue with save code:
                   System.out.println("File Selected:" + loadPrefs.toString());
                   Properties loadData = new Properties();
                   try {
                        loadData.load( new FileReader( loadPrefs.toString() ) );
                        _SitePropPanel.setLandfillClosed(new Boolean(loadData.getProperty("SITE CLOSED")));
                        _SitePropPanel.setCloseYear(loadData.getProperty("CLOSE YEAR"));
                        _SitePropPanel.setOpenYear(loadData.getProperty("OPEN YEAR"));
                        //_SitePropPanel.setCollectionRate(loadData.getProperty("COL RATE"));
                        _SitePropPanel.setGasRecoveryState(new Boolean(loadData.getProperty("GAS RECOV STATE")));
                   } catch (FileNotFoundException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                   } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                   System.out.println("File Loaded");
         }

    Hi sch,
    i've been figuring out what is the problem and i think i found it.
    Your saving the data with this.
    data.println("CLOSE YEAR="+_SitePropPanel.getCloseYear());
    data.println("OPEN YEAH="+_SitePropPanel.getOpenYear());
    //data.println("COL RATE = "+_SitePropPanel.getCollectionRate());
    data.println("GAS RECOV STATE="+_SitePropPanel.getGasRecoveryState());
    data.println("SITE CLOSED="+_SitePropPanel.getLandfillClosed());
    when trying to System.out the loadData (properties) you can see clearly that it prints out like this
    CLOSE=YEAR, OPEN=YEAH, etc etc
    so obvouisly your not setting correctly.
    it works this way.
    greetz Wiz
    import java.io.File;
    import java.io.FileNotFoundException;
    import java.io.FileOutputStream;
    import java.io.FileReader;
    import java.io.IOException;
    import java.io.PrintStream;
    import java.util.Properties;
    import javax.swing.JFileChooser;
    import javax.swing.JFrame;
    import javax.swing.JOptionPane;
    public class Tester {
          * @param args
         JFileChooser fc = new JFileChooser();
         JFrame f;
         public static void main(String[] args) {
              // TODO Auto-generated method stub
              new Tester();
         public Tester() {
              f = new JFrame();
              f.setSize(800, 600);
              f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              f.setVisible(true);
    //          SavePrefs();
              LoadPrefs();
         private void SavePrefs() {
              File SavePrefs;
              // get filename:
              fc.setDialogTitle("Select Filename For Site Data");
              int result = fc.showSaveDialog(f);
              if (result == JOptionPane.OK_OPTION) {
              SavePrefs = fc.getSelectedFile();
              // default file extension ".CMM"
              if (!SavePrefs.getName().endsWith(".CMM")) {
              // filename does not meet requirements:
              System.out.println("NO CMIMS in filename");
              SavePrefs = new File(SavePrefs.getAbsolutePath() + ".CMM");
              // continue with save code:
              System.out.println("File Selected:" + SavePrefs.toString());
              //Creates a .cmm file with all the data in it.
              FileOutputStream saveData;
              PrintStream data;
              try {
              saveData = new FileOutputStream(SavePrefs.toString());
              data= new PrintStream(saveData);
              data.println("CLOSEYEAR="+_SitePropPanel.getCloseYear());
              data.println("OPENYEAH="+_SitePropPanel.getOpenYear());
              //data.println("COL RATE = "+_SitePropPanel.getCollectionRate());
              data.println("GASRECOV STATE="+_SitePropPanel.getGasRecoveryState());
              data.println("SITECLOSED="+_SitePropPanel.getLandfillClosed());
              data.flush();
              data.close();
              saveData.flush();
              saveData.close();
              } catch (FileNotFoundException e) {
              // TODO Auto-generated catch block
              e.printStackTrace();
              } catch (IOException e) {
              // TODO Auto-generated catch block
              e.printStackTrace();
              System.out.println("File Saved");
              // not OK selected (cancel or.?)
              private void LoadPrefs() {
              File loadPrefs;
              // get filename:
              fc.setDialogTitle("Select Filename For Site Data");
              int result = fc.showOpenDialog(f);
              if (result == JOptionPane.OK_OPTION) {
              loadPrefs = fc.getSelectedFile();
              // default file extension ".CMM"
              if (!loadPrefs.getName().endsWith(".CMM")) {
              // filename does not meet requirements:
              System.out.println("NO CMIMS in filename");
              // continue with save code:
              System.out.println("File Selected:" + loadPrefs.toString());
              Properties loadData = new Properties();
              try {
              new _SitePropPanel();
              loadData.load( new FileReader( loadPrefs.toString() ) );
              System.out.println(loadData);
              _SitePropPanel.setLandfillClosed(new Boolean(loadData.getProperty("SITECLOSED")));
              _SitePropPanel.setCloseYear(loadData.getProperty("CLOSEYEAR"));
              _SitePropPanel.setOpenYear(loadData.getProperty("OPENYEAR"));
              //_SitePropPanel.setCollectionRate(loadData.getProperty("COL RATE"));
              _SitePropPanel.setGasRecoveryState(new Boolean(loadData.getProperty("GASRECOVSTATE")));
              } catch (FileNotFoundException e) {
              // TODO Auto-generated catch block
              e.printStackTrace();
              } catch (IOException e) {
              // TODO Auto-generated catch block
              e.printStackTrace();
              System.out.println("File Loaded");
    }

  • WRT350N - V2.00.20: Write access problem to SMB share from Mac OS X 10.6.2

    Hi everyone, i've got a problem trying to write a file on the SMB share of the wireless router WRT350N from a MAC OS X 10.6.2 Finder (but also from a Leopard).
    I've got no problem neither reading from mac or writing from win.
    I've tried to write by cp command from terminal without problem.
    Sorry for my english and thanks everyone,
     Mr Proc 

    Same issue on my WRT610N V2. I am using iMac Intel running 10.6.2. Error -36 prompted when copying files to the USB share disk from the Finder. Working fine when on PC running XP.
    Another issue is DDNS can't report the router IP to DynDNS.com although it status that the update is successful and completed. After updated, the router's IP is still different to the IP shown on the DynDNS.com. I need to type the IP manually to the DynDNS.com
    Hope the new firmware would fix these problems.
    Thanks 
    Message Edited by rickysuper on 11-27-2009 12:00 AM

  • Write file problem

    Hi, guys
    I have a problem to write a file using PrintWriter. What I want to do is my program takes file name and path, if the same name file exist in the folder, data ppended at the end of the existing file, otherwise it generates the new file.
    File file_out = new File(path, title);
           //System.out.println(file_out.getName());
           if (fileName_out.getName().equals(""))
             JOptionPane.showMessageDialog(this,"Invalid File name",
                   "Invalid File nmae",JOptionPane.ERROR_MESSAGE);
             return(false);
         else
                   try
                        boolean created = file_out.createNewFile();
                        if(created)
                            fileOutput = new PrintWriter(new FileWriter(fileName_out));
                            return(true);
                        else
                            fileOutput = new PrintWriter(new FileWriter(fileName_out,true));
                            fileOutput.println("File Name"+"\t"+"Slope(m)"+"\t"+"y-intercept(b)"+"\t"+"Correlation(r)");
                            return(true);
                    catch (IOException exc)
                         System.err.println("Can not open the file " );
                         return(false);
                    }I don't know what's wrong with, when I run this program, it doesn't make any file and issues NullPointerException.
    Anybody got solutions?
    Thanks a lot,

    File file_out = new File(path, title);
           //System.out.println(file_out.getName());
           if (fileName_out.getName().equals("")) Is there a reason why you assign something to the variable file_out and then start working with a different variable fileName_out? Which you probably haven't assigned anything to, leading to NullPointerExceptions?

  • MSI-8340 cd writer speed problem

    I have just got an MSI cd writer 8340 - yet i am having a problem with the speed - as it is not burning 40X cd with 40X but only with 32X also i have a cd rewritable 10X speed and it is only allowing me to burn at 8X
    I used different cd writing software and still had the same thing - i used nero and clone cd
    I have firmware 100d - should i update
    Does anyone has the same problem?
    Please help me
    Also on the msi product archive there is no MSI-8340 writer there is an ms-8340A is that the same thing

    Paul:
    Please tell us your Specs
    May be you have not too much Ram to run XP, let's say 256 MB or less? Does the recordable cds support that speed?
    What's the recording software you are using?
    Regards

  • Ds writer example problem

    Whenever I run the "DS writer.vi" example VI, I get an error pop-up stating "Cwdss has caused and error in MFC42.DLL" Cwdss will now close." I am running Windows ME and LabVIEW7. Has anyone else experienced this?

    This doesn't really answer your question, but I would recommend ditching Windows ME, if you can afford to do so. It is an orphaned product, which is full of problems and was simply a money grab by MS before they could release Windows XP.
    Good luck,
    -Jim

  • Using javascript to call a signed applet's read/write functions problem.

    Hi, I wan't to use javascript to call the read/write functions of my signed java applet.
    The applet can read/write fine, if its called from inside the applet, but when I make public functions to do the read/write and then call those functions from javascript, i get the old security exception.
    Has anyone done this before?
    Thanks

    From what I understand is that for example file IO can only be done if the current method
    has this privilege and the stack that called the current method had this privilege.
    Javascript doesn't have any privilege and calling methods that do file IO directly from
    javascript should not work, this bug was fixed in 1.4.2.
    The workarround AccessController.doPrivileged(new PrivilegedAction() { might allso be
    fixed in later versions since changing the privileges of currently executing code is
    someting that should not be possible when the currently executing code is called from
    "untrusted" (javascript) code.
    http://forum.java.sun.com/thread.jsp?forum=63&thread=524815
    second post

Maybe you are looking for