java file streams question

i am trying to send a class file from one machine to another one. i can send a java file and execute on client machine. but, i am not able to execute the class file that is sent through the network. i do not understand if there is a problem with kind of stream i am using or just trying to do something impossible.

my client code looks like:
import java.net.*;
import java.io.*;

class net2{

public static void main(String[]args){
        try{
        Socket s = new Socket("csp03.csci.unt.edu", 2345);
        File outputFile = new File("A.class");
        InputStream is = s.getInputStream();
        InputStreamReader isr = new InputStreamReader(is);
        BufferedReader br = new BufferedReader(isr);
        FileOutputStream fout = new FileOutputStream(outputFile);
        int x;

        //int x = br.read();
        //System.out.print(x);
        //fout.write((char)x);
        //System.out.print((char)x);
        while((x = br.read())!= -1){
                //x = br.read();

                //if(x != -1){
                fout.write(x);
                //System.out.print((char)x);
                //}


        }
        //System.out.println();
        s.close();
        fout.close();
        }

        catch (IOException e){
        System.out.println(e);
        }
}
}


server code looks like

import java.net.*;
import java.io.*;

class net1{
public static void main (String[]args)
{

try {
        FileInputStream fis = new FileInputStream("A.class");
        BufferedInputStream bis = new BufferedInputStream(fis);
        ServerSocket ss = new ServerSocket(2345);
        Socket s = ss.accept();
        PrintStream ps = new PrintStream(s.getOutputStream());

        int i;
//      i = bis.read();
//      ps.print((char)i);
        while((i = bis.read())!= -1)
        {
        //i = bis.read();
        // line is in original one.ps.print((char)i);
         ps.print(i);

        }

        s.close();
}


catch(Exception e) {
System.out.println(e);
}
}
}


PLEASE HELP IN THIS REGARD. I WILL BE HAPPY TO GIVE EXTRA POINTS FOR QUICK ANSWERS.

Thanks in advance.
valivetikAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Mayank SAssociate Director - Product EngineeringCommented:
The class file will not run in case the platforms, etc are different.

Mayank.
0
msterjevCommented:
How do you execute the class file? Does that class implements some interface or extends some other class (in that case you should send all the classes). DId the client code compile?

I don't know what are you trying to do, but that is not the way for using distributed classes. You should create one interface and distribute that interface to the all network clients during the compile time. After that during runtime you should use the URLClassLoader for downloading the specific implementations of the created interface, implementing that way method encapsulation!
0
antons061400Commented:
InputStreamReader isr = new InputStreamReader(is);

create reader with default encoding. I expect that this will corrup the classfile.

As you are transferring bytes use just
DataInputSteam and DataOutputStream for the transfere.
0
Cloud Class® Course: SQL Server Core 2016

This course will introduce you to SQL Server Core 2016, as well as teach you about SSMS, data tools, installation, server configuration, using Management Studio, and writing and executing queries.

objectsCommented:
As msterjev mentions the oimportant thing here is how you are executing the class file.
There is no problem with sending the class file over the net, but you need to give more details about how u r executing it, and the problem you are having executing it.
0
evimalCommented:
fine,
   U get the class file byte by byte. since by checking that
       x = br.read())!= -1  it checks for the socket connection is closed.

so U just add one more line in your server while sending the file.
       
       while((i = bis.read())!= -1)
       {
        ps.print(i);
       }
       ps.print('#');//to send as a EOF-mark.


on client side

       while((x = br.read())!= -1)
       {
            if ((char)x == '#')
             {
              fout.close();
              break;
             }
            else  fout.write(x);
       }
        sock.close();

it will work. but if the connection is closed before file transmission it won't work.
0
Mayank SAssociate Director - Product EngineeringCommented:
What if there happens to be a byte '#' in the class file itself?

Mayank.
0
valivetikAuthor Commented:
The class file may contain something like  to "say hello" or may have a small method that opens a file and puts something in it and closes the stream. In both the cases, it is not supposed to depend on any other class than ones that come with Standard Java API.

For now, my class file (or java file instead does print "hello"). So, what i expect is that this class file is sent over network and is recieved by the other end. I type Java A.class (the class file that is sent to me over network) and get output "hello". When I execute this program I get an error saying

Exception in thread "main" java.lang.ClassFormatError: A2 (Bad magic number)
        at java.lang.ClassLoader.defineClass0(Native Method)
        at java.lang.ClassLoader.defineClass(ClassLoader.java:509)
        at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:123)
        at java.net.URLClassLoader.defineClass(URLClassLoader.java:246)
        at java.net.URLClassLoader.access$100(URLClassLoader.java:54)
        at java.net.URLClassLoader$1.run(URLClassLoader.java:193)
        at java.security.AccessController.doPrivileged(Native Method)
        at java.net.URLClassLoader.findClass(URLClassLoader.java:186)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:306)
        at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:265)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:262)
        at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:322)


Yeah, thats a long error message.

The platforms are same.

Regarding the application I am trying to work on is to send a class file over net. The class file ( the corresponding java file i mean) should be able to open a file a write some data to it.


0
objectsCommented:
As mentioned above you are using a Reader/Writer for transferring a binary file. They are designed for transferring text files, you should be using streams instead.
0
valivetikAuthor Commented:
okay. i will do that and get back to you. thanks for your input.
0
kokchoon78Commented:
Hi,

   Opps! a bit late....

Here is a example code for binary file copy :

public void sendFile(String filename, Socket s) throws Exception
{
  File f = new File(filename);
  if ((! f.exists()) || f.isDirectory())
  {
     System.out.println("Invalid File");
  }
  else
  {
     FileInputStream fis = new FileInputStream(f);
     OutputStream oos = s.getOutputStream();

     int eof = -1;
     while ((eof = fis.read()) != -1)
     {
       oos.write(eof);
     }
     oos.flush();
     oos.close();    
  }
}

hth,
Kok Choon.
0
kokchoon78Commented:
Here is the example for server to read the binary file sent by client :

InputStream is = socket.getInputStream();

String outFilePath = "C:\\temp\\out.txt";
File outFile = new File ( outFilePath );
FileOutputStream fos = new FileOutputStream(outFile);
int eof = -1;

while ((eof = is.read()) != -1)
{
  fos.write(eof);
}
fos.flush();
fos.close();

regards,
Kok Choon.
0
objectsCommented:
You might want to use a buffer to improve performance a bit though :)
0
kokchoon78Commented:
hmmm... correct!

public void sendFile(String filename, Socket s) throws Exception
{
 File f = new File(filename);
 if ((! f.exists()) || f.isDirectory())
 {
    System.out.println("Invalid File");
 }
 else
 {
    FileInputStream fis = new FileInputStream(f);
    OutputStream oos = s.getOutputStream();

    int eof = -1;
    byte[] buffer = new byte[1024];
    while (fis.read( buffer ) != -1)
    {
      oos.write(buffer);
    }
    oos.flush();
    oos.close();    
 }
}

And for server :

String outFilePath = "C:\\temp\\out.txt";
File outFile = new File ( outFilePath );
FileOutputStream fos = new FileOutputStream(outFile);
int eof = -1;

byte[] buffer = new byte[1024];
while (is.read( buffer ) != -1)
{
 fos.write(buffer);
}
fos.flush();
fos.close();


regards,
Kok Choon.
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
valivetikAuthor Commented:
I read a lill bit about streams and read all the comments here. Thanks for everyone. I really appreciate your effort.

Mr.Kok Choon - thanks for taking time and posting code. Here is my code. It works. Please suggest me if there are more corrections/modifications that can be made to it.
Thanks!!


Client Program

import java.net.*;
import java.io.*;

class net2{

public static void main(String[]args){
        try{
        Socket s = new Socket("csp03.csci.unt.edu", 2345);
        File outputFile = new File("A.class");
        InputStream is = s.getInputStream();
        FileOutputStream fout = new FileOutputStream(outputFile);
        int x;
        while((x = is.read())!= -1){
                fout.write(x);
        }
        s.close();
        fout.close();
        }
        catch (IOException e){
        System.out.println(e);
        }
}
}


Server Program

import java.net.*;
import java.io.*;

class net1{
public static void main (String[]args)
{

try {
        FileInputStream fis = new FileInputStream("A.class");
        BufferedInputStream bis = new BufferedInputStream(fis);
        ServerSocket ss = new ServerSocket(2345);
        Socket s = ss.accept();
PrintStream ps = new PrintStream(s.getOutputStream());
        int i;
        while((i = bis.read())!= -1)
        {
         ps.write(i);
        }
        s.close();
}
catch(Exception e) {
System.out.println(e);
}
}
}






0
valivetikAuthor Commented:
Thanks for your time.
0
kokchoon78Commented:
hi, to improve the performance, you may need to add-in the buffer while write and read.

   byte[] buffer = new byte[1024];
   while (fis.read( buffer ) != -1)
   {
     oos.write(buffer);
   }


   byte[] buffer = new byte[1024];
   while (is.read( buffer ) != -1)
   {
      fos.write(buffer);
   }

And, in the Server Program, remember to flush and close the PrintStream instance.

  ps.flush();
  ps.close();


hth,
Kok Choon.
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Java

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.