我正在用javafx编写一个java数据传输程序。一切运行正常,但是当我点击我的程序中场景2中的"发送"按钮(以及场景3中的接收按钮)时,它会崩溃我的程序而不会出现任何错误。 这是我的Scene 2的控制器类。 问题可能在于函数" send()"。这是用于创建端口和传输文件的代码。
public class ControllerSc2 {
@FXML
public Button browsebut,sendbut,backbut;
@FXML
public TextField Path;
@FXML
public TextArea info;
public Socket socket;
public String path,name;
public void browseButton() {
FileChooser fc = new FileChooser();
File sf = fc.showOpenDialog(null);
if(sf != null){
Path.setText(path = sf.getAbsolutePath());
info.setText("Name: "+ (name = sf.getName()) +"\n" + "Size: "+ sf.length() +"Bytes \n" +"From Path: "+ sf.getAbsolutePath() +"\n");
}
else{
Path.setPromptText("please choose something!");
info.setPromptText("No File was chosen!");
}
}
public void back(){
Main.ShowScene1();
}
//NOTE!!!!!!: critical problem in send function
public void send() throws IOException{
ServerSocket serverSocket = new ServerSocket(5000);//this is the code making the program listen to connection from a port
info.setText("Waiting for connection");
socket = serverSocket.accept();//waiting connection
info.setText("Connected....");
/*DataOutputStream dout=new DataOutputStream(socket.getOutputStream());//
dout.writeUTF(name);//transfer name */
//File transferFile = new File(path);
File transferFile = new File("C:\\Users\\longt\\IdeaProjects\\a.docx");
byte[] bytearray = new byte[(int) transferFile.length()];
FileInputStream fin = new FileInputStream(transferFile);
BufferedInputStream bin = new BufferedInputStream(fin);
bin.read(bytearray, 0, bytearray.length);
OutputStream os = socket.getOutputStream();
System.out.println("Sending Files...");
os.write(bytearray, 0, bytearray.length);
os.flush();
socket.close();
System.out.println("File transfer complete");
}
} `