fzprog
fzprog

Reputation: 69

File Sharing in java

Hi I am making File Transferring Application in java.. but problem is that the receiver side code fixed the extension and path but I want the user can own set own path to save the receiving file..Every thing is working fine but I want that the user can set path according to his need..


File Sender

public class FileSender{
public static void main(String ar[])throws Exception{
    Socket clientSocket=new Socket("192.168.*.1",4444);
    //InputStream in=clientSocket.getInputStream();
    OutputStream out=clientSocket.getOutputStream();

    //PrintStream ps=new PrintStream(out);

    FileInputStream fis=new FileInputStream("D://tesing.java");
    int x=0;
    while(true){
        x=fis.read();
        if(x==-1)break;
        out.write(x);
    }
    out.close();
}
}

File Receiver

public class FileReceiver{
public static void main(String ar[])throws Exception{
    ServerSocket ss=new ServerSocket(4444);
    Socket clientSocket=ss.accept();
    InputStream in=clientSocket.getInputStream();
    //OutputStream out=clientSocket.getOutputStream();
    FileOutputStream fos=new FileOutputStream("E:\\recftp.txt");
    int x=0;
    while(true){
        x=in.read();
        if(x==-1)break;
        fos.write(x);
    }
    fos.close();
}
}

I want like this (user only sets folder and all types of files save in it) enter image description here

Upvotes: 1

Views: 2492

Answers (2)

fzprog
fzprog

Reputation: 69

FileServer

import java.net.*;
import java.io.*;
public class fileserver extends javax.swing.JFrame {

 /** Creates new form fileserver */
ServerSocket  ss;
Socket s;
File fadd;
public fileserver() {
initComponents();
//this.pack();
this.setVisible(true);
jFileChooser2.setVisible(true);
jProgressBar1.setVisible(false);
jButton2.setVisible(true);
jLabel1.setVisible(false);
this.setSize(600,200);
try
{
ss=new ServerSocket(4444);
 System.out.println("Yesssss, No problem with My Server");
 conn();
  }
  catch(Exception e){}
  }

 @SuppressWarnings("unchecked")
  // //GEN-BEGIN:initComponents
  private void initComponents() {

 jFileChooser1 = new javax.swing.JFileChooser();
  jButton1 = new javax.swing.JButton();
 jButton2 = new javax.swing.JButton();
 jFileChooser2 = new javax.swing.JFileChooser();
 jProgressBar1 = new javax.swing.JProgressBar();
 jLabel1 = new javax.swing.JLabel();

setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setTitle("Futuristic FileSharing (Server)");

 jButton1.setText("Browse File");
 jButton1.addActionListener(new java.awt.event.ActionListener() {
 public void actionPerformed(java.awt.event.ActionEvent evt) {
  jButton1ActionPerformed(evt);
  }
  });

  jButton2.setText("Send to User");
  jButton2.addActionListener(new java.awt.event.ActionListener() {
  public void actionPerformed(java.awt.event.ActionEvent evt) {
 jButton2ActionPerformed(evt);
 }
  });

  jFileChooser2.addActionListener(new java.awt.event.ActionListener() {
  public void actionPerformed(java.awt.event.ActionEvent evt) {
  jFileChooser2ActionPerformed(evt);
  }
  });

  jLabel1.setText("Sending…");

    javax.swing.GroupLayout layout = new javax.swing.GroupLayout  (getContentPane());
  getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
   .addGroup(layout.createSequentialGroup()
    .addGroup(layout.createParallelGroup     (javax.swing.GroupLayout.Alignment.TRAILING)
 .addGroup(layout.createSequentialGroup()
   .addContainerGap()
    .addComponent(jFileChooser2, javax.swing.GroupLayout.PREFERRED_SIZE,    javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
    .addGroup(layout.createSequentialGroup()
    .addGap(145, 145, 145)
   .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 122,     javax.swing.GroupLayout.PREFERRED_SIZE)
   .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 186, Short.MAX_VALUE)
    .addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 127,     javax.swing.GroupLayout.PREFERRED_SIZE)))
   .addContainerGap(171, Short.MAX_VALUE))
    .addGroup(layout.createSequentialGroup()
     .addGap(198, 198, 198)
     .addComponent(jLabel1)
     .addGap(18, 18, 18)
    .addComponent(jProgressBar1, javax.swing.GroupLayout.PREFERRED_SIZE,          javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
      .addContainerGap(295, Short.MAX_VALUE))
    );
    layout.setVerticalGroup(
   layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
   .addGroup(layout.createSequentialGroup()
   .addGap(65, 65, 65)
    .addGroup(layout.createParallelGroup   (javax.swing.GroupLayout.Alignment.TRAILING)
   .addComponent(jButton2)
    .addComponent(jButton1))
    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
    .addGroup(layout.createParallelGroup   (javax.swing.GroupLayout.Alignment.LEADING)
    .addComponent(jLabel1)
    .addComponent(jProgressBar1, javax.swing.GroupLayout.PREFERRED_SIZE,   javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 11,   Short.MAX_VALUE)
    .addComponent(jFileChooser2, javax.swing.GroupLayout.PREFERRED_SIZE,    javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
  );

 pack();
  }// //GEN-END:initComponents

  private void jFileChooser2ActionPerformed(java.awt.event.ActionEvent evt)    {//GEN-FIRST:event_jFileChooser2ActionPerformed
 if(jFileChooser2.CANCEL_OPTION==1)
 {
jFileChooser2.setVisible(false);
  this.setSize(600, 200);
 jButton1.setEnabled(true);
  jButton2.setVisible(false);
  }
  fadd=jFileChooser2.getSelectedFile();
 jButton2.setVisible(true);
  //jButton1.setVisible(false);
  if((fadd==null)||(fadd.getName().equals("")))
 {
jFileChooser2.setVisible(false);
 this.setSize(600, 200);
    jButton1.setEnabled(true);
    jButton2.setVisible(false);
    }
   }//GEN-LAST:event_jFileChooser2ActionPerformed

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt)      {//GEN-FIRST:event_jButton1ActionPerformed
    jFileChooser2.setVisible(true);
 this.setSize(800, 500);
jButton1.setEnabled(false);
  }//GEN-LAST:event_jButton1ActionPerformed

  private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-       FIRST:event_jButton2ActionPerformed
   jProgressBar1.setVisible(true);
   jLabel1.setVisible(true);
   this.setSize(600,200);
    doit();
     }//GEN-LAST:event_jButton2ActionPerformed

     /**
    * @param args the command line arguments
     */
    public static void main(String args[]) {
     java.awt.EventQueue.invokeLater(new Runnable() {
    public void run() {
    new fileserver();
     }
     });

    }
    void doit(){
     try{
     jProgressBar1.setValue(10);
      byte [] mybytearray  = new byte [(int)fadd.length()];

     FileInputStream fis = new FileInputStream(fadd);
     BufferedInputStream bis = new BufferedInputStream(fis);

   bis.read(mybytearray,0,mybytearray.length);
    OutputStream os = s.getOutputStream();
     jProgressBar1.setValue(20);
    ObjectOutputStream snd=new ObjectOutputStream(os);
      jProgressBar1.setValue(30);
    msg m=new msg();
     System.out.println("Sending…");
     jProgressBar1.setValue(40);
    m.setarray(mybytearray);
    jProgressBar1.setValue(50);
     m.setname(fadd.getName());
     jProgressBar1.setValue(70);

    snd.writeObject(m);
   snd.flush();
   System.out.println("Done…");
    jProgressBar1.setValue(100);
     }
    catch(Exception i){
   System.out.println("\nChal bhag Kaam nai Hua!");
    }
     }
     void conn(){
         try{
          System.out.println("Pending request (Server)");
         s=ss.accept();
       }
        catch(Exception e){
       System.out.println("Error in connection"+e);}
       }
     // Variables declaration – do not modify//GEN-BEGIN:variables
       private javax.swing.JButton jButton1;
      private javax.swing.JButton jButton2;
    private javax.swing.JFileChooser jFileChooser1;
        private javax.swing.JFileChooser jFileChooser2;
     private javax.swing.JLabel jLabel1;
    private javax.swing.JProgressBar jProgressBar1;
   // End of variables declaration//GEN-END:variables
   }
   class msg1 implements Serializable
    {
  boolean flag;
  int size;
  String name;
  byte[] mess;

  msg1(){
  flag=false;
  size=0;
 name="Server";
  }

 void setarray(byte[] b){
 mess=b;
 }

  void setname(String str){
  name=str;
   }

 byte[] getarray(){
 return(mess);
 }

 String getname(){
 return(name);
 }
}

FileClient

 import java.net.*;
 import java.io.*;
 import javax.swing.*;
  public class fileclient extends javax.swing.JFrame {

 /** Creates new form fileclient */
 File fadd;
 BufferedOutputStream bos;
  ObjectInputStream recv;
   Socket  s;
  public fileclient() {
  initComponents();
  this.setVisible(true);
 this.pack();
 jLabel1.setText("Waiting……..");
this.setSize(400, 200);
   try{
   s=new Socket("localhost",4444);
    }
   catch(Exception e){
   System.out.println(""+e);
    }
    service();
    }

 @SuppressWarnings("unchecked")
  // //GEN-BEGIN:initComponents
    private void initComponents() {

   jLabel1 = new javax.swing.JLabel();

  setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
  setTitle("Futuristic FileSharing (Client)");

   jLabel1.setText("File Recieved…");

   javax.swing.GroupLayout layout = new javax.swing.GroupLayout   (getContentPane());
   getContentPane().setLayout(layout);
    layout.setHorizontalGroup(
 layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
  .addGroup(layout.createSequentialGroup()
  .addGap(129, 129, 129)
  .addComponent(jLabel1)
  .addContainerGap(191, Short.MAX_VALUE))
   );
   layout.setVerticalGroup(
  layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
   .addGroup(layout.createSequentialGroup()
   .addContainerGap()
  .addComponent(jLabel1)
 .addContainerGap(535, Short.MAX_VALUE))
   );

 pack();
 }
  public static void main(String args[]) {
 java.awt.EventQueue.invokeLater(new Runnable() {
 public void run() {
  new fileclient();
  }
   });
  }
 void service(){
  int size = 10000000;
 byte [] barr  = new byte [size];
 try{
 InputStream is = s.getInputStream();

   recv=new ObjectInputStream(is);
  msg m= new msg();
  m=(msg)recv.readObject();
  barr=m.getarray();
  String fname=m.getname();
 jLabel1.setText("File Recieved: "+fname);
  destfile();
 bos.write(barr);
 bos.flush();
 bos.close();
 }catch(Exception i){
 System.out.println("\nClient: Problem  "+i);
  }
  }
  void destfile()
   {
  this.setSize(600,400);
  JFileChooser fc=new JFileChooser();
  fc.setFileSelectionMode(JFileChooser.FILES_ONLY);
  int x=fc.showSaveDialog(this);
 if(x== JFileChooser.CANCEL_OPTION || x ==JFileChooser.ABORT){
 jLabel1.setText("## Operation Aborted by User ##");
this.setSize(400,200);
  return;
 }
  jLabel1.setText("Saved As : "+fc.getSelectedFile());
  fadd=fc.getSelectedFile();
  if((fadd==null)||(fadd.getName().equals(""))){
jLabel1.setText("! File Not Saved or Wrongly saved !");
  }
    else{
  try{
  FileOutputStream fos = new FileOutputStream(fadd);
  bos = new BufferedOutputStream(fos);
   }catch(IOException i){
 System.out.println("PROB!"+i);
  }
 }

 }

   // Variables declaration – do not modify//GEN-BEGIN:variables
   private javax.swing.JLabel jLabel1;
    // End of variables declaration//GEN-END:variables
   }
   class msg implements Serializable
  {
 boolean flag;
 int size;
  String name;
  byte[] mess;

 msg(){
  flag=false;
  size=0;
  name="Server";
 }

 void setarray(byte[] b){
  mess=b;
  }

 void setname(String str){
  name=str;
   }

   byte[] getarray(){
  return(mess);
  }

  String getname(){
 return(name);
 }
 }

Upvotes: 0

chiastic-security
chiastic-security

Reputation: 20520

The question isn't absolutely clear: do you want the receiver to specify the filename, or do you want the sender to be able to specify it, so that the receiver names the file accordingly? For the moment I'm assuming it's the former. See further down if not.

The problem you've got is that what you're sending is just the file data as a big indistinguishable blob. You'll need to send the filename too; but you can't do that as it stands, because the receiver won't know what's filename and what's data.

I'd suggest opening a connection in both directions, and running a small protocol:

  1. Receiver requests file.
  2. Sender sends filename.
  3. Receiver sends acknowledgement and requests file data.
  4. Sender sends file data.

The alternative would be to send the filename at the beginning, followed by a null character (0x00), since a null isn't allowed in a filename on any typical filesystem. The receiver would be able to treat everything up to (but not including) the first null as the filename; then discard the null; then treat everything else as the file data.

If it's the latter...

The easiest approach would be to take the filename as a parameter on the command line. That's what the String[] args parameter to the main method is for. If you run the application with a command-line argument, it'll turn up in your application as args[0]. You can use args.length to find out how many, if any, arguments were supplied on the command line.

Upvotes: 1

Related Questions