将我的字节数组读入输入流

时间:2011-05-05 02:42:53

标签: java swing bytearray inputstream

每当我想在动作监听器中运行fileToByteArray方法时,它就会要求try catch语句。当我运行代码时,我输入的文件不会被分解为字节。我已经尝试了一切。有人可以帮忙吗?

// ClientFrame.java
//
// Informatics 45 Spring 2010
// Code Example: GUI with Simple Sockets


import java.awt.*;
import java.awt.event.*;

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

import javax.swing.*;


public class ClientFrame extends JFrame implements ClientProtocolListener
{
    private JTextField nameField;
    private JTextField addressField;
    private JTextField portField;
    private JButton connectButton;
    private DefaultListModel resultsListModel;
    static Socket sockets; 
    File files;

    private ClientProtocol clientProtocol;
     static File file; 


    public ClientFrame()
    {
        setSize(500, 700);
        setTitle("Informatics 45 GUIs and Sockets Example (Client)");
        setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);

        buildUI();

        clientProtocol = null;
    }


    private void buildUI()
    {
        GridBagLayout layout = new GridBagLayout();
        getContentPane().setLayout(layout);

        JLabel nameLabel = new JLabel("Your name: ");
        layout.setConstraints(
            nameLabel,
            new GridBagConstraints(
                0, 0, 1, 1, 0.0, 0.0,
                GridBagConstraints.WEST, GridBagConstraints.NONE,
                new Insets(10, 10, 10, 10), 0, 0));
        getContentPane().add(nameLabel);

        nameField = new JTextField();
        layout.setConstraints(
            nameField,
            new GridBagConstraints(
                1, 0, 1, 1, 1.0, 0.0,
                GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL,
                new Insets(10, 10, 10, 10), 0, 0));
        getContentPane().add(nameField);

        JLabel addressLabel = new JLabel("Address:");
        layout.setConstraints(
            addressLabel,
            new GridBagConstraints(
                0, 1, 1, 1, 0.0, 0.0,
                GridBagConstraints.WEST, GridBagConstraints.NONE,
                new Insets(10, 10, 10, 10), 0, 0));
        getContentPane().add(addressLabel);

        addressField = new JTextField();
        layout.setConstraints(
            addressField,
            new GridBagConstraints(
                1, 1, 1, 1, 1.0, 0.0,
                GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL,
                new Insets(10, 10, 10, 10), 0, 0));
        getContentPane().add(addressField);

        JLabel portLabel = new JLabel("Port: ");
        layout.setConstraints(
            portLabel,
            new GridBagConstraints(
                0, 2, 1, 1, 0.0, 0.0,
                GridBagConstraints.WEST, GridBagConstraints.NONE,
                new Insets(10, 10, 10, 10), 0, 0));
        getContentPane().add(portLabel);

        portField = new JTextField();
        layout.setConstraints(
            portField,
            new GridBagConstraints(
                1, 2, 1, 1, 1.0, 0.0,
                GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL,
                new Insets(10, 10, 10, 10), 0, 0));
        getContentPane().add(portField);

        connectButton = new JButton("Connect");
        connectButton.addActionListener(
            new ActionListener()
            {
                public void actionPerformed(ActionEvent e)
                {
                    connect();
                    //getFileChooser();
                    try {
                        fileToByteArray(file);
                    } catch (IOException e1) {
                        // TODO Auto-generated catch block
                        e1.printStackTrace();
                    } 

                }
            });
        layout.setConstraints(
            connectButton,
            new GridBagConstraints(
                1, 3, 1, 1, 0.0, 0.0,
                GridBagConstraints.EAST, GridBagConstraints.NONE,
                new Insets(10, 10, 10, 10), 0, 0));
        getContentPane().add(connectButton);

        JLabel statusLabel = new JLabel("Status");
        layout.setConstraints(
            statusLabel,
            new GridBagConstraints(
                0, 4, 1, 1, 0.0, 0.0,
                GridBagConstraints.WEST, GridBagConstraints.NONE,
                new Insets(10, 10, 10, 10), 0, 0));
        getContentPane().add(statusLabel);

        resultsListModel = new DefaultListModel();
        JList resultsList = new JList(resultsListModel);
        JScrollPane resultsScroller = new JScrollPane(resultsList);
        layout.setConstraints(
            resultsScroller,
            new GridBagConstraints(
                0, 5, 2, 1, 1.0, 1.0,
                GridBagConstraints.CENTER, GridBagConstraints.BOTH,
                new Insets(10, 10, 10, 10), 0, 0));
        getContentPane().add(resultsScroller);
    }


    private void connect()
    {
        String name = getNameFromField();
        String address = getAddressFromField();
        int port = getPortFromField();

        if (name == null || address == null || port == -1)
        {
            return;
        }

        connectButton.setEnabled(false);
        resultsListModel.addElement("Connecting to " + address + " port " + port);

        clientProtocol = new ClientProtocol(name, address, port);
        clientProtocol.addClientProtocolListener(this);

        Thread clientThread = new Thread(clientProtocol);
        clientThread.start();
    }


    private String getNameFromField()
    {
        String name = nameField.getText().trim();

        if (name.length() == 0)
        {
            JOptionPane.showMessageDialog(
                this, "Please specify a name", "Validation Error",
                JOptionPane.ERROR_MESSAGE);

            return "";
        }

        return name;
    }


    private String getAddressFromField()
    {
        String address = addressField.getText().trim();

        if (address.length() == 0)
        {
            JOptionPane.showMessageDialog(
                this, "Please specify an address", "Validation Error",
                JOptionPane.ERROR_MESSAGE);

            return null;
        }

        return address;
    }


    private int getPortFromField()
    {
        int port;

        try
        {
            port = Integer.parseInt(portField.getText());
        }
        catch (NumberFormatException e)
        {
            JOptionPane.showMessageDialog(
                this, "Please specify a number for the port between 0 and 65535",
                "Validation Error", JOptionPane.ERROR_MESSAGE);

            return -1;
        }

        return port;
    }


    public void connectionEstablished(final String serverAddress, final int serverPort)
    {
        EventQueue.invokeLater(
            new Runnable()
            {
                public void run()
                {
                    resultsListModel.addElement("Connected to " + serverAddress + " port " + serverPort);
                }
            });
    }


    public void okayReceived(final String otherName)
    {
        EventQueue.invokeLater(
            new Runnable()
            {
                public void run()
                {
                    resultsListModel.addElement("OKAY received from " + otherName);
                }
            });
    }


    public void connectionClosed()
    {
        EventQueue.invokeLater(
            new Runnable()
            {
                public void run()
                {
                    resultsListModel.addElement("Connection closed");
                    connectButton.setEnabled(true);
                }
            });
    }


    public void protocolFailed(final Exception failureReason)
    {
        EventQueue.invokeLater(
            new Runnable()
            {
                public void run()
                {
                    resultsListModel.addElement(
                        "Protocol failure: " + failureReason.getMessage());

                    connectButton.setEnabled(true);
                }
            });
    }


    public void dispose()
    {
        if (clientProtocol != null)
        {
            clientProtocol.removeClientProtocolListener(this);
            clientProtocol.close();
        }

        super.dispose();
    }

    public void getFileChooser (){
        FileChooser chooseFile = new FileChooser(); 
        file = chooseFile.getFile();
    }

     public byte[] fileToByteArray(File fileArray) 
     throws IOException 
        {
            if (fileArray.exists() == false)
            {
                System.out.println ("Please specify a file to read ");
                return null; 
            }
            int fileLength = (int) fileArray.length();

            byte[] fileBytes = new byte[fileLength]; 

            FileInputStream input = new FileInputStream (fileArray);

            int offset = 0;

            while (offset < fileLength)
            {
                int nextChunkSize = Math.min(65536, fileLength - offset);
                offset += input.read(fileBytes, offset, nextChunkSize);
            }

            input.close();

            System.out.println ("The files lenth was " + fileLength);

            System.out.println ("The first 10 bytes are :")
;

        for (int i = 0; i <10; i++)
     {
         System.out.print (Integer.toHexString (((int)fileBytes[i])&0xFF).toUpperCase());
         System.out.print(" "  ); 
     }



            return fileBytes; 
        }

     public void sendFile(byte[] byteArray){


     }



}

1 个答案:

答案 0 :(得分:1)

如果你不介意包含JAR,Apache Commons IO有readFileToByteArray()