java退出应用程序导致无限循环
我制作了一个简单的java应用程序来打印文本文件,然后应该终止。 我试图使用返回状态修复,但根本不起作用。所以我使用了system.exit(0),但它不是退出应用程序,而是进入无限循环。。。 这是我的密码:有人能告诉我怎么了吗java退出应用程序导致无限循环,java,android,Java,Android,我制作了一个简单的java应用程序来打印文本文件,然后应该终止。 我试图使用返回状态修复,但根本不起作用。所以我使用了system.exit(0),但它不是退出应用程序,而是进入无限循环。。。 这是我的密码:有人能告诉我怎么了吗 package com.example.testprinterdemo; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import andr
package com.example.testprinterdemo;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import com.pda3505.Service.CaptureService;
import com.pda3505.printer.PrinterClassSerialPort;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
public class MainActivity extends Activity {
public static PrinterClassSerialPort printerClass = null;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
init();
printerClass.write(new byte[] { 0x1d, 0x21,0x00,0x00});
printerClass.write(new byte[] { 0x1b, 0x26, 0x00 });
BufferedReader reader = null;
try {reader = new BufferedReader(new FileReader("/mnt/sdcard/temp.txt"));}
catch (FileNotFoundException e) {e.printStackTrace();}
String line = null;
try {line = reader.readLine();}
catch (IOException e) {e.printStackTrace();}
while(line!=null) {
printerClass.printText(line);
printerClass.printText("\n");
try {line = reader.readLine();}
catch (IOException e) {e.printStackTrace();}
}
system.exit(0);
}
private void init() {
printerClass = new PrinterClassSerialPort(new Handler());
printerClass.open(this);
Intent newIntent = new Intent(MainActivity.this, CaptureService.class);
newIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startService(newIntent);
}
}
在您的方法中,行从不为空,它可以是”
,也可以是”
或“\n”
等,但从不为空。因此,倾听长度,打破循环
当您可以将代码放在单个try块下时,请避免使用多个try-catch块。请正确定义变量的作用域,不要在未使用的作用域之外声明变量,因为这会给JAVA垃圾收集器带来问题/
请调试你的程序。你会想到的。是的,我同意@f1sh,它显然来自你的while循环,所以你应该能够调试并发现问题。尝试将你的while循环包含在Try子句中,该子句抛出IOException<代码>尝试{while((line=reader.readLine())!=null){..}}捕获{..}。要退出,请在退出(0)之前尝试使用
finish()
。line.readLine()永远不会返回null,有关更多信息,请参阅我的答案!!!使用finish();系统出口(0);它起作用了:()()()))非常感谢
try{
//never hard code the file path in Android.
String filePath = Environment.getExternalStorageDirectory().getAbsolutePath()+File.separator+"temp.txt";
BufferedReader reader = new BufferedReader(new FileReader(filePath));
while (true){
String line = reader.readLine();
if(line.length() > 0){
printerClass.printText(line);
printerClass.printText("\n");
}else{
break;
//you can use return too
}
}
}catch (IOException e){
e.printStackTrace();
}