java中的文件共享

时间:2015-08-13 20:02:59

标签: java sockets java-io

您好我在java中制作文件传输应用程序..但问题是接收方端代码修复了扩展和路径,但我希望用户可以拥有自己的路径来保存接收文件。每件事情都运行正常但是我希望用户可以根据自己的需要设置路径..

文件发件人

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();
}
}

文件接收器

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();
}
}

我想要这样(用户只设置文件夹并保存所有类型的文件) enter image description here

2 个答案:

答案 0 :(得分:1)

这个问题并不是很清楚:你希望接收者指定文件名,还是希望发送者能够指定它,以便接收者相应地命名文件?目前我假设它是前者。如果没有,请进一步查看。

您遇到的问题是,您发送的内容只是文件数据,是一个难以区分的大块。您还需要发送文件名;但是你不能这样做,因为接收者不知道什么是文件名和什么数据。

我建议在两个方向上打开一个连接,并运行一个小协议:

  1. 接收方请求文件。
  2. 发件人发送文件名。
  3. 接收方发送确认并请求文件数据。
  4. 发件人发送文件数据。
  5. 另一种方法是在开头发送文件名,然后是空字符(0x00),因为在任何典型文件系统上的文件名中都不允许使用null。接收器能够将所有内容(但不包括)第一个null视为文件名;然后丢弃空值;然后将其他所有内容视为文件数据。

    如果是后者......

    最简单的方法是将文件名作为参数放在命令行上。这是String[] args方法的main参数的用途。如果使用命令行参数运行应用程序,它将在您的应用程序中以args[0]形式出现。您可以使用args.length来查找命令行中提供的参数数量(如果有)。

答案 1 :(得分:0)

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);
 }
 }