这个问题在这里已有答案:
所以我有两个方法,其代码我将在下面提出。第一种方法调用第二种方法,第二种方法负责打开读取数据的文件并将其发送到dataoutputstream请求变量。
我的问题是,如果文件不存在于文件夹中,我无法打印任何堆栈跟踪,或者如果调用第二个方法,则无法打印有关异常的信息。
但是,如果我不注释第一个方法中的注释行(它做同样的事情)并且根本不调用第二个方法,我能够在我的日志文件中看到日志,堆栈跟踪和文件未找到异常。
任何人都可以建议为什么会这样吗?即使调用第二个方法,我也需要能够使用找不到文件的异常:
public void addBodySend(String metadata, File file, String pMode) throws Exception{
try{
request = new DataOutputStream(httpConn.getOutputStream());
String post_data = crlf+twoHyphens + boundary + crlf+"Content-Disposition: form-data; name=\"properties\""+crlf+crlf+metadata+crlf+twoHyphens+boundary+crlf;
String fileName = file.getName();
post_data = post_data + "Content-Disposition: form-data; name=\"file\"; filename=\"" + fileName + "\""+crlf+"Content-Type: application/octet-stream"+crlf+crlf;
request.writeBytes(post_data);
if(pMode == "LOCAL_DIR"){
this.getLocalFile(file);
}
/*fileInputStream = new FileInputStream(file);
bufferedInputStream = new BufferedInputStream(fileInputStream);
byte[] buffer;
buffer = new byte[1024];
int bytesRead=0;
while((bytesRead = bufferedInputStream.read(buffer)) != -1){
request.write(buffer,0,bytesRead);
request.flush();
}
request.writeBytes(crlf+twoHyphens + boundary + twoHyphens + crlf);
request.flush();*/
}catch(Exception ex){
this.sendStatus = false;
ex.printStackTrace();
log.writeln("Error while sending post request",0);
for (StackTraceElement ste : Thread.currentThread().getStackTrace()) {
log.writeln(ste.toString(),0);
}
}finally{
if(bufferedInputStream!=null){
try{
bufferedInputStream.close();
}catch(Exception ex){
log.writeln("Error closing bufferred input stream",0);
}
}
if(request!=null){
try{
request.close();
}catch(Exception ex){
log.writeln("Error closing post request",0);
}
}
}
}
public void getLocalFile(File file) {
try{
fileInputStream = new FileInputStream(file);
bufferedInputStream = new BufferedInputStream(fileInputStream);
byte[] buffer;
buffer = new byte[1024];
int bytesRead=0;
while((bytesRead = bufferedInputStream.read(buffer)) != -1){
request.write(buffer,0,bytesRead);
request.flush();
}
request.writeBytes(crlf+twoHyphens + boundary + twoHyphens + crlf);
request.flush();
this.sendStatus = true;
}catch(Exception ex){
this.sendStatus = false;
ex.printStackTrace();
log.writeln("Error while sending binary body",0);
for (StackTraceElement ste : Thread.currentThread().getStackTrace()) {
log.writeln(ste.toString(),0);
}
}finally{
if(bufferedInputStream!=null){
try{
bufferedInputStream.close();
}catch(Exception ex){
log.writeln("Error closing bufferred input stream",0);
}
}
}
}
尝试改变你比较这些字符串pMode
和"LOCAL_DIR"
的方式。代替
if(pMode == "LOCAL_DIR"){
this.getLocalFile(file);
}
做
if("LOCAL_DIR".equals(pMode)){
this.getLocalFile(file);
}
希望有所帮助