Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

x
?
Solved

java file streams question

Posted on 2003-03-25
16
Medium Priority
?
418 Views
Last Modified: 2012-06-27
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.
0
Comment
Question by:valivetik
  • 4
  • 4
  • 3
  • +4
16 Comments
 
LVL 30

Expert Comment

by:Mayank S
ID: 8208373
The class file will not run in case the platforms, etc are different.

Mayank.
0
 
LVL 3

Expert Comment

by:msterjev
ID: 8208384
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
 
LVL 4

Expert Comment

by:antons061400
ID: 8208401
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
Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
LVL 92

Expert Comment

by:objects
ID: 8208438
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
 

Expert Comment

by:evimal
ID: 8209147
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
 
LVL 30

Expert Comment

by:Mayank S
ID: 8209167
What if there happens to be a byte '#' in the class file itself?

Mayank.
0
 

Author Comment

by:valivetik
ID: 8214906
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
 
LVL 92

Expert Comment

by:objects
ID: 8214981
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
 

Author Comment

by:valivetik
ID: 8214989
okay. i will do that and get back to you. thanks for your input.
0
 
LVL 4

Expert Comment

by:kokchoon78
ID: 8223407
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
 
LVL 4

Expert Comment

by:kokchoon78
ID: 8223435
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
 
LVL 92

Expert Comment

by:objects
ID: 8223500
You might want to use a buffer to improve performance a bit though :)
0
 
LVL 4

Accepted Solution

by:
kokchoon78 earned 200 total points
ID: 8223553
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
 

Author Comment

by:valivetik
ID: 8232285
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
 

Author Comment

by:valivetik
ID: 8232286
Thanks for your time.
0
 
LVL 4

Expert Comment

by:kokchoon78
ID: 8235612
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

Featured Post

[Webinar] Database Backup and Recovery

Does your company store data on premises, off site, in the cloud, or a combination of these? If you answered “yes”, you need a data backup recovery plan that fits each and every platform. Watch now as as Percona teaches us how to build agile data backup recovery plan.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Introduction Java can be integrated with native programs using an interface called JNI(Java Native Interface). Native programs are programs which can directly run on the processor. JNI is simply a naming and calling convention so that the JVM (Java…
In this post we will learn different types of Android Layout and some basics of an Android App.
Viewers learn about the third conditional statement “else if” and use it in an example program. Then additional information about conditional statements is provided, covering the topic thoroughly. Viewers learn about the third conditional statement …
This tutorial covers a step-by-step guide to install VisualVM launcher in eclipse.
Suggested Courses
Course of the Month14 days, 7 hours left to enroll

580 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question