网路类装载器(服务端)
import java.io.*;
import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
import java.net.*;
import javax.swing.filechooser.FileFilter;
class ClassFilter extends FileFilter
{
public boolean accept( File pathName)
{
return pathName.getPath().endsWith(".class");
}
public String getDescription()
{
return "java's Class file *.class";
}
}
public class ServerClassGiver extends JFrame implements ActionListener
{
private ServerSocket sock;
private JTextField PathText = new JTextField("Please Input the class file");
private JButton BrowseBtn = new JButton("Browse");
private JButton AcceptBtn = new JButton("Accept");
private File fileToSend = null;
public ServerClassGiver( int port ) throws Exception
{
sock = new ServerSocket( port );
setDefaultCloseOperation( EXIT_ON_CLOSE );
setBounds( 0,0,200,300 );
AcceptBtn.setEnabled(false);
PathText.setEditable(false);
BrowseBtn.addActionListener(this);
AcceptBtn.addActionListener(this);
this.setLayout( new FlowLayout() );
this.getContentPane().add( PathText );
this.getContentPane().add( BrowseBtn );
this.getContentPane().add( AcceptBtn );
setVisible(true);
}
public void actionPerformed( ActionEvent e )
{
if( e.getActionCommand().equals("Browse"))
{
JFileChooser open = new JFileChooser();
open.setFileFilter( new ClassFilter() );
if( open.showOpenDialog( this ) == JFileChooser.APPROVE_OPTION )
{
fileToSend = open.getSelectedFile();
if( !fileToSend.exists() )
{
JOptionPane.showMessageDialog( this , "File does not exist!" ,
"Warnning!" , JOptionPane.WARNING_MESSAGE, null);
return;
}
PathText.setText( fileToSend.getPath());
if( !AcceptBtn.isEnabled() )
{
AcceptBtn.setEnabled(true);
}
}
}
else if( e.getActionCommand().equals("Accept"))
{
try
{
Socket client = sock.accept();
FileInputStream fin = new FileInputStream( fileToSend );
BufferedInputStream bin = new BufferedInputStream( fin );
BufferedOutputStream bout = new BufferedOutputStream(client.getOutputStream());
int b;
while( (b=bin.read())!=-1 )
{
bout.write(b);
}
bin.close();
bout.close();
JOptionPane.showMessageDialog( this , "Finished!" );
}
catch(Exception ex)
{
JOptionPane.showMessageDialog( this , ex.getMessage() );
}
}
}
public static void main(String [] args )throws Exception
{
new ServerClassGiver(80);
}
}