我正在尝试将一个audio file
从服务器传输到客户端并将其写入另一个文件。正在从客户端读取文件,但它正在读取文件的server
内容而忽略新行。例如,有一个像“我正在做客户端服务器程序”这样的文本,文件的下一行是“in Java”。服务器读取为“我正在做客户端服务器编程Java
”。我的问题是如何逐行阅读内容..
我的代码如下...
*
服务器
**try
{
` try
{
System.out.println("Im server waiting for client request");
ss=new ServerSocket(2005);
Socket s=ss.accept();
InputStream is = s.getInputStream( );//Input Stream
BufferedReader fileRead =new BufferedReader(new InputStreamReader(is));
String fname = fileRead.readLine( );
OutputStream os = s.getOutputStream( );//socket output stream
PrintWriter pw = new PrintWriter(os, true);
BufferedReader br = new BufferedReader(new FileReader(fname) );//read File
String str;//initiating string and StringBuffer
StringBuilder sb=new StringBuilder();
while((str = br.readLine()) != null) // reading line-by-line from file
{
sb.append(str);//append to stringBuffer sb
}
System.out.println("The string is in server" +sb);
pw.println(sb);
pw.flush();
pw.close();
is.close();
fileRead.close();
os.close();
pw.close();
br.close();
}
catch(Exception e)
{
e.getMessage();
e.getStackTrace();
e.getSuppressed();
}`
The Client side::
try {
System.out.println("Im client ..sending request");
Socket s=new Socket("127.0.0.1",2005);//Initiate Socket
System.out.println("Enter filename");
BufferedReader bw=new BufferedReader(new InputStreamReader(System.in));//Take fileName from keyBoard
String filename=bw.readLine();//Read filename into a string
OutputStream dout=new DataOutputStream(s.getOutputStream());//output Stream
PrintWriter pw=new PrintWriter(dout,true);
pw.println(filename);//write filename to socket
InputStream is = s.getInputStream( );//Input Stream
BufferedReader in =new BufferedReader(new InputStreamReader(is));
String clstr;
StringBuilder sd=new StringBuilder();
while((clstr=in.readLine())!=null)
{
sd.append(clstr);
//clstr=in.readLine();//Read String From socket into "clstr" string
}
System.out.println("The string in client is" +sd);
File f=new File("A://music/kin.txt");//Open a file
if(!f.exists())
f.createNewFile();//if not existed create it
try
{
//PrintWriter bf=new PrintWriter(new FileWriter(f)); //Write to a file
BufferedWriter bf=new BufferedWriter(new FileWriter(f));
//bf.append(clstr);
//bf.write(sd);
bf.append(sd);
bf.flush();
bf.close();
}
catch(Exception e)
{
e.getMessage();
e.getSuppressed();
e.getStackTrace();
}
System.out.println("The Content written is" +sd);
bw.close();
pw.close();
dout.close();
in.close();
is.close();
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}