Java 输入流问题-Android
我正在试图弄清楚为什么我的inputstream不能正常工作。我试图连接到服务器并获取一个JSON字符串并将其保存到变量inputJSON中,但是inputJOSN为空,因为我的inputstream无法正常工作。这行代码:Java 输入流问题-Android,java,android,Java,Android,我正在试图弄清楚为什么我的inputstream不能正常工作。我试图连接到服务器并获取一个JSON字符串并将其保存到变量inputJSON中,但是inputJOSN为空,因为我的inputstream无法正常工作。这行代码: inputJSON = ConvertByteArrayToString(getBytesFromInputStream(inputStr)); 似乎工作不正常,我不知道为什么?我确实认为getBytesFromInputStream方法中的长度变量存在问题。如果有,我不
inputJSON = ConvertByteArrayToString(getBytesFromInputStream(inputStr));
似乎工作不正常,我不知道为什么?我确实认为getBytesFromInputStream方法中的长度变量存在问题。如果有,我不确定这是不是或者如何修复它
下面是我的getBytesFromInputStream方法代码:
public static byte[] getBytesFromInputStream(InputStream is)
throws IOException {
// Get the size of the file
long length = is.available();
Log.e(LOG_TAG, "INPUTSTREAM LENGTH:"+length);
if (length > Integer.MAX_VALUE) {
// File is too large
}
// Create the byte array to hold the data
byte[] bytes = new byte[(int) length];
// Read in the bytes
int offset = 0;
int numRead = 0;
while (offset < bytes.length
&& (numRead = is.read(bytes, offset, bytes.length - offset)) >= 0) {
offset += numRead;
}
// Ensure all the bytes have been read in
if (offset < bytes.length) {
throw new IOException("Could not completely stream ");
}
// Close the input stream and return bytes
is.close();
return bytes;
}
以下是ConvertByteArrayToString的代码:
public String ConvertByteArrayToString(byte[] b) {
// byte[] to string
String input = new String(b);
return input;
}
以下是我为onCreate编写的代码:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Log.e(LOG_TAG, "Before OnCreate() Try");
try {
Log.e(LOG_TAG, "In OnCreate() Try");
socket = new Socket("23.23.175.213", 9000); //Port 1337
Log.e(LOG_TAG, "Created Socket");
dataOutputStream = new DataOutputStream(socket.getOutputStream());
Log.e(LOG_TAG, "Created DataOutputStream");
dataInputStream = new DataInputStream(socket.getInputStream());
Log.e(LOG_TAG, "Created DataInputStream");
//out = new OutputStream();
out = socket.getOutputStream();
inputStr = socket.getInputStream();
p = new Profile();
Log.e(LOG_TAG, "Created Profile Instance");
//Gets the local profile via JSON and converts into Profile type
Gson gson = new Gson();
Log.e(LOG_TAG, "Created Gson Instance" + "GetProfileJSONStr:" + p.getProfileJSONStr());
p = gson.fromJson(p.getProfileJSONStr(), Profile.class);
setProfile(p);
Log.e(LOG_TAG, "Converted Profile to JSON");
//Gson gson = new Gson();
Log.e(LOG_TAG, "Before: outputJSON = gson.toJson(p);");
outputJSON = gson.toJson(p).toString();
outputJSON = removeExcessStr(outputJSON);
Log.e(LOG_TAG, "ProfilePicStr Base64:"+p.getProfilePicStr());
outputJSON = outputJSON.replace("Name","name");
outputJSON = outputJSON.replace("TagLine","message");
outputJSON = outputJSON.replace("Title","title");
outputJSON = outputJSON.replace("Company", "company");
outputJSON = outputJSON.replace("Industry","industry");
outputJSON = outputJSON.replace("WhatIDo","whatido");
outputJSON = outputJSON.replace("WhoDoIWantToMeet","meetwho");
outputJSON = outputJSON.replace("WHOOZNEAR_PROFILEPIC","photo");
outputJSON = outputJSON.replaceAll("[c][o][n][t][e][n][t][:][/][/][a-zA-Z0-9]+[/][a-zA-Z0-9]+[/][a-zA-Z0-9]+[/][a-zA-Z0-9]+[/][a-zA-Z0-9]+", getPicBase64Str()); /*"helloworld2"*/
if (!outputJSON.contains(",\"photo\":")) {
outputJSON = outputJSON.replace("}",",\"photo\":"+"\"IconnexUs\"}");
outputJSON = outputJSON.replace("}",",\"photo\":"+"\""+getPicBase64Str()+"\"}");
outputJSON = outputJSON.replace("}",",\"status\":\"enabled\"}");
}
else {
outputJSON = outputJSON.replace("}",",\"status\":\"enabled\"");
}
outputJSONserv = "{\"to\":\"broadcast\",\"type\":\"1\",\"payload\":"+outputJSON+"}";
Log.e(LOG_TAG, "Created outputJSON:" + outputJSON);
Log.e(LOG_TAG, "Created outputJSON Server:" + outputJSONserv);
JSONObject outObject = new JSONObject();
try {
outObject.put("photo", "hello");
outObject.put("type", "50");
outObject.put("payload", outputJSON);
outputJSON = gson.toJson(outObject).toString();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Log.e(LOG_TAG, "Value of PROFILEPIC STRING FROM PROFILEMAP: "+profileMap.get("WHOOZNEAR_PROFILEPIC"));
p.setProfilePicStr(ConvertandSetImagetoBase64(profileMap.get("WHOOZNEAR_PROFILEPIC")));
//String headerJSON = gson.toJson(outObject).toString();
outputJSON = outputJSON.substring(nthOccurrence(outputJSON, '{', 2)-1, nthOccurrence(outputJSON, '}', 1)-1);
outputstrwr = new PrintWriter(new OutputStreamWriter(socket.getOutputStream()), true);
outputstrwr.write(outputJSONserv);
Log.e(LOG_TAG, "Base64 String:"+p.getProfilePicStr());
Log.e(LOG_TAG, "Sent dataOutputStream");
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Log.e(LOG_TAG, "Before initEventHandlers");
initEventHandlers();
Log.e(LOG_TAG, "After initEventHandlers");
//refreshViewModels();
Log.e(LOG_TAG, "Start Repeat Thread");
rt = new Thread(new RepeatingThread());
rt.start();
Log.e(LOG_TAG, "Started Repeat Thread");
}
refreshViewModels的代码:
public void refreshViewModels(String inputJSON) {
try {
ListView servicesListView = (ListView) this
.findViewById(R.id.profilesListView);
String[] from = new String[] { "profilePic", "neighborName",
"tagLine" };
int[] to = new int[] { R.id.avatar, R.id.username, R.id.email };
// prepare the list of all records
List<HashMap<String, Object>> fillMaps = new ArrayList<HashMap<String, Object>>();
List<Profile> profiles = new ArrayList<Profile>();
// Clear the position mapping list and reset it
this.posMap.clear();
Log.i(LOG_TAG, "NEW inputJSON: " + inputJSON);
inputJSON = getPayloadStr(inputJSON);
Log.i(LOG_TAG, "NEW inputJSON2: " + inputJSON);
JSONArray profileArray = new JSONArray(inputJSON);
for (int i=0; i<profileArray.length(); i++) {
JSONObject jsonObject = profileArray.getJSONObject(i);
Gson gson = new Gson();
Profile p = gson.fromJson(gson.toJson(jsonObject).toString(), Profile.class);
profiles.add(p);
}
int pos = 0;
// Creates the fillMaps list for the listAdapter
Log.i(LOG_TAG, "Profiles size: " + profiles.size());
//showToast("Profiles size: " + profiles.size());
for (Profile p : profiles) {
// Create mapping for list adapter
HashMap<String, Object> map = new HashMap<String, Object>();
map.put("profilePic",
p.getAttributeValue("photo")== null? "Not Set" : p
.getAttributeValue("photo"));
map.put("neighborName",
p.getAttributeValue("Name") == null? "Not Set" : p
.getAttributeValue("Name"));
map.put("tagLine",
p.getAttributeValue("TagLine") == null? "Not Set" : p
.getAttributeValue("TagLine"));
fillMaps.add(map);
// Reset the postion mapping
this.posMap.put(pos++, p);
}
ListAdapter servicesListAdapter = new myAdapter(this, fillMaps,
R.layout.listitem, from, to);
servicesListView.setAdapter(servicesListAdapter);
} catch (Exception e) {
Log.e(LOG_TAG, "Error making list adapter: " + e.getMessage());
}
}
任何帮助都将不胜感激。在多个Java平台上,我发现InputStream.available不可靠。如果你看的话,也是这样。我会尽量避免使用这种方法。在多个Java平台上,我发现InputStream.available不可靠。如果你看的话,也是这样。我会尽量避免使用这种方法。首先,您应该验证InputStream是否有数据-不要依赖可用的方法。而且您一次读取整个流,所以不需要使用while循环 我建议您使用BufferedReader 或返回字节[]
public static byte[] getBytesFromInputStream(InputStream is)
.....
ByteArrayOutputStream bos=new ByteArrayOutputStream();
BufferedInputStream bin=new BufferedInputStream(is);
int numRead=0;
byte []bytes=new byte[1024];
while( (numRead=bin.read(bytes))>0)
{
bos.write(bytes, 0, numRead);
}
bos.flush();
byte []totalBytes=bos.toByteArray();
.....
return totalBytes;
}首先,您必须验证InputStream是否有数据-不要依赖可用的方法。而且您一次读取整个流,所以不需要使用while循环 我建议您使用BufferedReader 或返回字节[]
public static byte[] getBytesFromInputStream(InputStream is)
.....
ByteArrayOutputStream bos=new ByteArrayOutputStream();
BufferedInputStream bin=new BufferedInputStream(is);
int numRead=0;
byte []bytes=new byte[1024];
while( (numRead=bin.read(bytes))>0)
{
bos.write(bytes, 0, numRead);
}
bos.flush();
byte []totalBytes=bos.toByteArray();
.....
return totalBytes;
}这是inputstream网络流吗?什么是输出可用?这是输入流网络流吗?什么是可用的输出?
public static String getStringFromInputStream(InputStream is)
throws IOException {
StringBuffer sb=new StringBuffer();
BufferedReader reader=null;
String line=null;
try{
reader=new BufferedReader(new InputStreamReader(is));
while( (line=reader.readLine()) !=null){
sb.append(line);
}
}catch(Exception ex){
//
}finally{
if(reader!=null){
try{
reader.close();
}catch(Exception ex) { }
}
}
return sb.toString();
}
public static byte[] getBytesFromInputStream(InputStream is)
.....
ByteArrayOutputStream bos=new ByteArrayOutputStream();
BufferedInputStream bin=new BufferedInputStream(is);
int numRead=0;
byte []bytes=new byte[1024];
while( (numRead=bin.read(bytes))>0)
{
bos.write(bytes, 0, numRead);
}
bos.flush();
byte []totalBytes=bos.toByteArray();
.....
return totalBytes;