android several ways to read the contents of a file by line

  • 2020-06-01 11:00:32
  • OfStack

1. The simple version


 import java.io.FileInputStream;
void readFileOnLine(){
String strFileName = "Filename.txt";
FileInputStream fis = openFileInput(strFileName);
StringBuffer sBuffer = new StringBuffer();
DataInputStream dataIO = new DataInputStream(fis);
String strLine = null;
while((strLine =  dataIO.readLine()) != null) {
    sBuffer.append(strLine + " \n");
}
dataIO.close();
fis.close();
}

2. The concise version


// Reads the contents of a text file
    public static String ReadTxtFile(String strFilePath)
    {
        String path = strFilePath;
        String content = ""; // File content string
            // Open the file
            File file = new File(path);
            // if path It's a parameter that's passed in, and you can do it 1 Non - directory judgment
            if (file.isDirectory())
            {
                Log.d("TestFile", "The File doesn't not exist.");
            }
            else
            {
                try {
                    InputStream instream = new FileInputStream(file);
                    if (instream != null)
                    {
                        InputStreamReader inputreader = new InputStreamReader(instream);
                        BufferedReader buffreader = new BufferedReader(inputreader);
                        String line;
                        // The branch read
                        while (( line = buffreader.readLine()) != null) {
                            content += line + "\n";
                        }               
                        instream.close();
                    }
                }
                catch (java.io.FileNotFoundException e)
                {
                    Log.d("TestFile", "The File doesn't not exist.");
                }
                catch (IOException e)
                {
                     Log.d("TestFile", e.getMessage());
                }
            }
            return content;
    }

3. apk for long-term use, with regular data

1. Read the contents of the file line by line


// First of all define 1 Is used to save the contents of the read file
class WeightRecord {
        String timestamp;
        float weight;
        public WeightRecord(String timestamp, float weight) {
            this.timestamp = timestamp;
            this.weight = weight;
           
        }
    }
   
// Began to read
 private WeightRecord[] readLog() throws Exception {
        ArrayList<WeightRecord> result = new ArrayList<WeightRecord>();
        File root = Environment.getExternalStorageDirectory();
        if (root == null)
            throw new Exception("external storage dir not found");
        // So let's go to the file
        File weightLogFile = new File(root,WeightService.LOGFILEPATH);
        if (!weightLogFile.exists())
            throw new Exception("logfile '"+weightLogFile+"' not found");
        if (!weightLogFile.canRead())
            throw new Exception("logfile '"+weightLogFile+"' not readable");
        long modtime = weightLogFile.lastModified();
        if (modtime == lastRecordFileModtime)
            return lastLog;
        // file exists, is readable, and is recently modified -- reread it.
        lastRecordFileModtime = modtime;
        // The file is then converted to a byte stream for reading
        FileReader reader = new FileReader(weightLogFile);
        BufferedReader in = new BufferedReader(reader);
        long currentTime = -1;
        // Read line by line
        String line = in.readLine();
        while (line != null) {
            WeightRecord rec = parseLine(line);
            if (rec == null)
                Log.e(TAG, "could not parse line: '"+line+"'");
            else if (Long.parseLong(rec.timestamp) < currentTime)
                Log.e(TAG, "ignoring '"+line+"' since it's older than prev log line");
            else {
                Log.i(TAG,"line="+rec);
                result.add(rec);
                currentTime = Long.parseLong(rec.timestamp);
            }
            line = in.readLine();
        }
        in.close();
        lastLog = (WeightRecord[]) result.toArray(new WeightRecord[result.size()]);
        return lastLog;
    }
    // Parse every 1 line
    private WeightRecord parseLine(String line) {
        if (line == null)
            return null;
        String[] split = line.split("[;]");
        if (split.length < 2)
            return null;
        if (split[0].equals("Date"))
            return null;
        try {
            String timestamp =(split[0]);
            float weight =  Float.parseFloat(split[1]) ;
            return new WeightRecord(timestamp,weight);
        }
        catch (Exception e) {
            Log.e(TAG,"Invalid format in line '"+line+"'");
            return null;
        }
    }

2, save as a file


public boolean logWeight(Intent batteryChangeIntent) {
            Log.i(TAG, "logBattery");
            if (batteryChangeIntent == null)
                return false;
            try {
                FileWriter out = null;
                if (mWeightLogFile != null) {
                    try {
                        out = new FileWriter(mWeightLogFile, true);
                    }
                    catch (Exception e) {}
                }
                if (out == null) {
                    File root = Environment.getExternalStorageDirectory();
                    if (root == null)
                        throw new Exception("external storage dir not found");
                    mWeightLogFile = new File(root,WeightService.LOGFILEPATH);
                    boolean fileExists = mWeightLogFile.exists();
                    if (!fileExists) {
                        if(!mWeightLogFile.getParentFile().mkdirs()){
                            Toast.makeText(this, "create file failed", Toast.LENGTH_SHORT).show();
                        }
                        mWeightLogFile.createNewFile();
                    }
                    if (!mWeightLogFile.exists()) {
                        Log.i(TAG, "out = null");
                        throw new Exception("creation of file '"+mWeightLogFile.toString()+"' failed");
                    }
                    if (!mWeightLogFile.canWrite())
                        throw new Exception("file '"+mWeightLogFile.toString()+"' is not writable");
                    out = new FileWriter(mWeightLogFile, true);
                    if (!fileExists) {
                        String header = createHeadLine();
                        out.write(header);
                        out.write('\n');
                    }
                }
                Log.i(TAG, "out != null");
                String extras = createBatteryInfoLine(batteryChangeIntent);
                out.write(extras);
                out.write('\n');
                out.flush();
                out.close();
                return true;
            } catch (Exception e) {
                Log.e(TAG,e.getMessage(),e);
                return false;
            }
        }


Related articles: