我有一个ArrayList<Group> listOfGroups
.
这些组有 4 个字段 - String groupName, int lastActiveID, int firstID, String indicator
。我想编写一个方法来返回有关 listOfGroups 中所有组的信息。
这是我正在尝试的:
String theList="";
for(Group gr:listOfGroups){
theList+=gr.groupName+" "+gr.lastActiveID+" "+gr.firstID+" "+gr.indicator+"\n";
}
System.out.print(theList);
return theList;
当我调用该方法时,我只得到关于第一组的信息,第二次调用返回关于第二组的信息等等......是因为 \n 字符吗?
我放这个System.out.println(theList)
只是为了查看字符串包含的内容,并获得有关所有组的信息。这正是我想要的回报。
我该如何解决?
编辑:它应该是服务器和客户端。这是我的服务器:
package server;
import java.io.*;
import java.net.*;
public class Server {
public static void main(String[] args){
if(args.length!=1){
System.err.println("Usage: java Server <port number>");
System.exit(1);
}
int portNumber=Integer.parseInt(args[0]);
try(
ServerSocket serverSocket=new ServerSocket(portNumber);
Socket clientSocket=serverSocket.accept();
PrintWriter out=new PrintWriter(clientSocket.getOutputStream(),
true);
BufferedReader in=new BufferedReader(
new InputStreamReader(clientSocket.getInputStream()));
){
String command;
String response;
NNTPProtocol protocol=new NNTPProtocol();
while((command=in.readLine())!=null){
response=protocol.processCommand(command);
out.println(response);
}
}
catch(IOException e){
e.getMessage();
}
}
}
这是 NNTP 协议:
package server;
import java.io.*;
import java.util.ArrayList;
public class NNTPProtocol {
ArrayList<Group> listOfGroups=new ArrayList<Group>();
Iterator it=listOfGroups.iterator();
static int curPos=0;
String processCommand(String command){
if(command.equalsIgnoreCase("list")){
return getListOfGroups();
}
else return null;
}
String getListOfGroups(){
if(listOfGroups.isEmpty()){
try{
DataInputStream in=new DataInputStream(new BufferedInputStream(
new FileInputStream(
"C:\\Users\\Ivo\\Documents\\NetBeansProjects\\"
+ "NNTPServerClient\\GroupsInfo.txt")));
String groupName;
while(!(groupName=in.readUTF()).equals("end")){
listOfGroups.add(new Group(groupName, in.readInt(),
in.readInt(), in.readUTF()));
}
}catch(FileNotFoundException e){}
catch(IOException e){}
}
String theList="";
for(Group gr:listOfGroups){
theList+=(gr.groupName+" "+gr.lastActiveID+" "+
gr.firstID+" "+gr.indicator+"\n");
}
System.out.print(theList);
return theList;
}
}
和 Group 类:
package server;
public class Group {
String groupName;
String indicator;
int firstID;
int lastActiveID;
Group(String groupName, int firstID, int lastActiveID, String indicator){
this.groupName=groupName;
this.indicator=indicator;
this.firstID=firstID;
this.lastActiveID=lastActiveID;
}
}