我的任务是通过socket
发送文件。我正在提示要发送多少个文件。但总是抛出exception
。
这是代码:
public void soc_server() throws IOException {
servsock = new ServerSocket(55000);
sock = servsock.accept();
System.out.println("Hello Server");
Scanner sc = new Scanner(System.in);
**System.out.println("how many files to be sent: ");
String temp = sc.nextLine();
// i used to take integer here. Still it was throwing same exception.
int fileNumber = Integer.parseInt(temp);
sc.close();
sc = new Scanner(System.in);**
for (int x = 0; x < fileNumber; x++) {
System.out.println("Please enter the file name or file path ");
String s = sc.nextLine();
File file = new File(s);
if (file.exists())
System.out.println("File found");
else
System.out.println("File not found");
OutputStream out = sock.getOutputStream();
fileInputStream = new FileInputStream(s);
byte[] buffer = new byte[100 * 1024];
int bytesRead = 0;
System.out.println("sending file no: " + x);
while ((bytesRead = fileInputStream.read(buffer)) != -1) {
if (bytesRead > 0) {
out.write(buffer, 0, bytesRead);
totalSent += bytesRead;
System.out.println("sent " + (totalSent / 1024) + " KB "
+ ((System.currentTimeMillis() - time) / 1000)
+ " sec");
}
}
out.flush();
fileInputStream.close();
// sock.close();
out.close();
// servsock.close();
// servsock = new ServerSocket(55000);
// sock = servsock.accept();
pw = new PrintWriter(sock.getOutputStream(), true);
pw.print(s);
pw.flush();
pw.close();
}
sock.close();
servsock.close();
sc.close();
System.out.println("Sent " + (totalSent / 1024) + " kilobytes in "
+ ((System.currentTimeMillis() - time) / 1000) + " seconds");
}
例外:
Exception in thread "main" java.util.NoSuchElementException: No line found
at java.util.Scanner.nextLine(Scanner.java:1585)
at Server.soc_server(Server.java:41)
at Index.main(Index.java:21)
除了将要发送多少文件的提示行之外,其余代码都能正常工作。我真的很困惑为什么我在写作时遇到同样的异常:
String temp = sc.nextLine();
int fileNumber = sc.nextInt();
谢谢。
答案 0 :(得分:0)
在代码开头分配扫描程序: 删除以下行
sc.close();
sc = new Scanner(System.in);