Several ways to read the contents of a file on Android by line _android

Source: Internet
Author: User
Tags getmessage readable readline stringbuffer

First, simple version

Copy Code code as follows:

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

Second, concise version

Copy Code code as follows:

Reading content in a text file
public static string Readtxtfile (String strFilePath)
{
String path = strFilePath;
String content = ""; File content string
Open File
File File = new file (path);
If path is an argument passed over, you can make a 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;
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;
}

Third, apk for long time use, and regular data

1, read the contents of the file line by row

Copy Code code as follows:

First, define a data type to hold the contents of the Read file
Class Weightrecord {
String timestamp;
float weight;
Public Weightrecord (String timestamp, float weight) {
This.timestamp = timestamp;
This.weight = weight;

}
}

Start reading
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");
First find 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;
Then convert the file into a byte stream read
FileReader reader = new FileReader (weightlogfile);
BufferedReader in = new BufferedReader (reader);
Long currenttime =-1;
Read-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 ' older than 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 each row
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 file

Copy Code code as follows:

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 Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.