簡體   English   中英

java退出應用程序導致無限循環

[英]java exit app causes infinite loop

我制作了一個簡單的 java 應用程序來打印一個文本文件,然后應該終止。 我嘗試使用 return 語句,但根本不起作用。 所以我使用了 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);

    }

}
    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();
    }

在您的方法中, line 永遠不會為空,它要么是""要么是" ""\\n"等,但永遠不會為空。 所以聽長度並打破循環

當您可以將代碼置於單個 try 塊下時,請避免使用多個 try catch 塊。 並且請正確定義變量的范圍,不要在不使用的范圍之外聲明變量,因為它會導致 JAVA 垃圾收集器/

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM