日期:2014-05-20 浏览次数:20906 次
public class Test{
public static void main(String[] args) {
try {
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream("H:/Server.java")));
String line = null ;
StringBuffer buf = new StringBuffer() ;
while( null != (line = br.readLine()) ){
buf.append(line+"\n");
}
System.out.println(buf.toString());
br.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
if( writeSocket.isConnected() ){
try {
outStream = writeSocket.getOutputStream() ;
send = new BufferedWriter(new OutputStreamWriter(outStream));
readFile = new BufferedReader(new InputStreamReader(new FileInputStream(file))) ;
String line = null ;
while( null != (line = readFile.readLine()) ){
send.write(line+System.getProperty("line.separator"));
send.newLine();
send.flush();
}
} catch (IOException e) {
e.printStackTrace();
} finally{
; /**备用通道,以保证Exception不会停止掉程序运行*/
}
}// end if
public class GainFile {
public static void main(String[] args) {
GainFile g = new GainFile();
g.receiveFile();//接收文件,接收时,在控制台显示文件内容
}
///////////////////////////////////////////////////
private ServerSocket server ;
private Socket receiveFileSocket ;
private StringBuffer buf ;
public GainFile() {
try {
server = new ServerSocket(9000) ;
} catch (IOException e) {
e.printStackTrace();
}
}
public void receiveFile(){
System.out.println("------等待客户端连接-------");
InputStream readIn = null ;
BufferedReader br = null ;
try {
receiveFileSocket = server.accept() ;
System.out.println("---------连接成功!-------");
Thread.sleep(1000);
System.out.println("---------开始接收 数据-----");
readIn = receiveFileSocket.getInputStream() ;
br = new BufferedReader(new InputStreamReader(readIn));
String line = null ;
while( null != (line = br.readLine()) ){
System.out.println(line);
buf.append(line) ;
}
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
finally{
try{
br.close();
readIn.close();
}
catch(IOException ioErr){ioErr.printStackTrace(); }
}
}
}
结果:
------等待客户端连接-------
---------连接成功!-------
---------开始接收 数据-----
import java.io.IOException; /*他接收到了Client读取文本后传来的这句话,然后报错*/
Exception in thread "main" java.lang.NullPointerException
at GainFile.receiveFile(GainFile.java:44)
at GainFile.main(GainFile.java:16)
while( null != (line = br.readLine()) ){
System.out.println(line);
buf.append(line) ;
}