我已经制作了一个简单的Java应用程序来打印文本文件然后应该终止。 我试图使用return statemend但根本没用。所以我使用了system.exit(0),但不是退出应用程序,它进入无限循环...... 这是我的代码:有人可以告诉我出了什么问题吗?
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);
}
}
答案 0 :(得分:0)
>>> import os
>>> path = "path to a word document"
>>> os.path.isfile(path)
True
>>> os.path.splitext(path)[1] == ".docx" # test if the extension is .docx
True
在您的方法中,行永远不会为空,它可以是 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();
}
,也可以是""
或" "
等,但永远不会为空。所以听长度并打破循环
如果您可以将代码置于单个try块下,请避免使用多个try catch块。请正确调整变量范围,不要在不使用变量的范围之外声明变量,因为它会导致JAVA垃圾收集器出现问题/