How to read last four lines form the file? - android

Am using following code to read last four lines from the file but return first line to null why? How to solve this problem? Please help me?
public void read(){
StringBuilder text = new StringBuilder();
File sdCard = Environment.getExternalStorageDirectory();
File dir = new File (sdCard.getAbsolutePath()+File.separator+"GPS");
dir.mkdirs();
String fname = "gps.txt";
File file = new File (dir, fname);
String[] last4 = new String[4];
int count=0;
try {
BufferedReader br = new BufferedReader(new FileReader(file));
while(br.ready()){
last4[count++%4]=br.readLine();
}
for (int i=0; i<4;i++){
text.append(last4[(i+count)%4]);
text.append('\n');
}
br.close();
}
catch (IOException e) {
e.printStackTrace();
}
}

You have to check if file exists. According to your code copy paste this,
public void read() throws FileNotFoundException{
StringBuilder text = new StringBuilder();
String fname = "asdf.txt";
String path = Environment.getExternalStorageDirectory()+File.separator+"GPS"+File.separator+fname;
//You have to check if file exists
File file = new File(path);
if(!file.exists()){
//TODO do smth if your file doesnt exist
return;
}
BufferedReader br = null;
String[] last4 = new String[4];
int count=0;
try {
String sCurrentLine;
br = new BufferedReader(new FileReader(path));
while ((sCurrentLine = br.readLine()) != null ) {
String str = sCurrentLine;
last4[count%4] = str;
count++;
}
for (int i=0; i<4;i++){
text.append(last4[i]);
text.append('\n');
}
System.out.println(text.toString());
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null)br.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}

Try This.
private static BufferedReader innerReader;
private static BufferedReader innerReader1;
private static final int UNTIL_LINE = 4;
public static int countLine(Reader reader) throws IllegalArgumentException
{
int countLine = 0;
if(reader == null)
{
throw new IllegalArgumentException("Null reader");
}
String line;
innerReader1 = new BufferedReader(reader);
try
{
while((line = innerReader1.readLine()) != null)
{
countLine++;
}
}catch(IOException e){}
return countLine;
}
public static List<String> loadFile(Reader reader, int countLine)
throws IllegalArgumentException{
List<String> fileList = new ArrayList<String>();
if(reader == null)
{
throw new IllegalArgumentException("Null Reader");
}
String line;
int thisLine = 0;
innerReader = new BufferedReader(reader);
try
{
while((line = innerReader.readLine()) != null)
{
if (line == null || line.trim().isEmpty())
throw new IllegalArgumentException(
"Line Empty");
thisLine++;
if(thisLine > countLine-UNTIL_LINE)
{
fileList.add(line);
}
}
} catch (IOException e) {
}
return fileList;
}
To test code.
int lines = 0;
List<String> test = new ArrayList<String>();
try {
lines = countLine(new FileReader("YourFile.txt"));
} catch (IOException e1) {
e1.printStackTrace();
}
try {
test = loadFile(new FileReader("YourFile.txt"), lines);
} catch (IOException e) {
e.printStackTrace();
}
for(String s : test)
{
System.out.println(s);
}
Full file example:
1 Line
2 Line
3 Line
4 Line
5 Line
6 Line
Result:
3 Line
4 Line
5 Line
6 Line

Are you sure the file exists and you have read access? It is odd that you are creating the parent directory before reading. Check your logcat for the stacktrace. Also, make sure you declared the "android.permission.WRITE_EXTERNAL_STORAGE" permission in your AndroidManifest.
I wrote the following method real quick. Should work fine for you.
public static String[] tail(File file, int tail) throws IOException {
BufferedReader reader = new BufferedReader(new FileReader(file));
List<String> lines = new ArrayList<>();
for (String line = reader.readLine(); line != null; line = reader.readLine()) {
lines.add(line);
}
reader.close();
return lines.subList(Math.max(0, lines.size() - tail), lines.size()).toArray(new String[tail]);
}
Example usage:
try {
File gps = new File(Environment.getExternalStorageDirectory(), "GPS/gps.txt");
String[] lastFourLines = tail(gps, 4);
} catch (IOException e) {
// Are you sure the file exists?
// Did you declare "android.permission.WRITE_EXTERNAL_STORAGE" permission?
}

Related

Android Studio - Why does a string array cause my program to stop?

I have been working on this for a while and I am about to pull my hair out!!
If I use this...
public void readFile() {
BufferedReader buffReader = null;
StringBuilder result = new StringBuilder();
try {
FileInputStream fileIn = openFileInput("VariableStore.txt");
buffReader = new BufferedReader(new InputStreamReader(fileIn));
String line;
while ((line = buffReader.readLine()) != null) {
result.append(line);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
assert buffReader != null;
buffReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
String resultString = result.toString();
String[] controlString = resultString.split("$");
// String wb = controlString[4];
// String sb = controlString[5];
((Button) this.findViewById(R.id.wakeButton)).setText(resultString);
// ((Button) this.findViewById(R.id.sleepButton)).setText(sb);
// ((Button)this.findViewById(R.id.wakeButton)).setText(result);
// ((Button)this.findViewById(R.id.wakeButton)).setText(result);
// ((Button)this.findViewById(R.id.wakeButton)).setText(result);
}
The Button.setText works fine with "resultString" or with "result" which is a string I have input formatted as xxx$xxx$xxx$xxx$xxx so when I read it back in with the readFile() I want to use .Split and put it into an array "controlString" and then assign the array elements to my widgets i.e. setText(controlString[0]); but if I so much as even uncomment the lines String wb = controlString[4]; or String sb = controlString[5]; my program crashes. Why wont the array elemts work here?
Here is my writeFile().... (Which works perfectly.
public void writeFile() {
BufferedWriter buffWriter = null;
String wb = ((Button)this.findViewById(R.id.wakeButton)).getText().toString();
String sb = ((Button)this.findViewById(R.id.sleepButton)).getText().toString();
String tb = ((EditText)this.findViewById(R.id.textHoursBetween)).getText().toString();
String ti = ((EditText)this.findViewById(R.id.textIncrementTime)).getText().toString();
String td = ((EditText)this.findViewById(R.id.textIncrementDays)).getText().toString();
String writeString = wb + "$" + sb + "$" + tb + "$" + ti + "$" + td;
try {
FileOutputStream fileOut = openFileOutput("VariableStore.txt", Context.MODE_PRIVATE);
buffWriter = new BufferedWriter(new OutputStreamWriter(fileOut));
try {
buffWriter.write(writeString);
} catch (IOException e) {
e.printStackTrace();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}finally {
try {
assert buffWriter != null;
buffWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
I found the problem...
Instead of this:
String[] controlString = resultString.split("$");
I had to use this:
String[] controlString = resultString.split(Pattern.quote("$"));

Saving int values to SD and read them

I have succesfully saved int values to sd but cant read. It always gives numberformat information. I made all logics, but cant find why it gives error.
Here is my code ;
this my constant
private final static String EXTERNAL_FILES_DIR = "ARDROID";
private final static String FILE_NAME = "turkcell.txt";
private boolean isThereAnySavedFile = false;
when this method called, it tries to open file, if file does not exist, create the file
public void anySavedDataInSD() {
String textFromSD = String.valueOf(read());
if (isThereAnySavedFile) {
int numberOfSendedSMS = Integer.parseInt(textFromSD.toString());
numberOfSendedSMS++;
writeToSD(String.valueOf(numberOfSendedSMS));
} else {
int first=60;
String g = String.valueOf(first);
writeToSD(g);
}
}
this method for writing
private void write(File file, String msg) {
FileOutputStream outputStream = null;
try {
outputStream = new FileOutputStream(file);
outputStream.write(msg.getBytes());
Logger.info("oldu bu kez");
} catch (IOException e) {
Logger.info("oldu bu kez2" + e);
} finally {
Logger.info("oldu bu kez3");
try {
if (outputStream != null)
outputStream.close();
} catch (IOException exception) {
}
}
}
this methof for reading
public StringBuilder read() {
StringBuilder textBuilder = new StringBuilder();
BufferedReader reader = null;
try {
File externalFilesDir = getExternalFilesDir(EXTERNAL_FILES_DIR);
File file = new File(externalFilesDir, FILE_NAME);
Logger.info("oldu2");
reader = new BufferedReader(new FileReader(file));
String line;
while ((line = reader.readLine()) != null) {
textBuilder.append(line);
textBuilder.append("\n");
}
isThereAnySavedFile = true;
} catch (FileNotFoundException e) {
Logger.info("oldu3");
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return textBuilder;
}

Android : Reading File

I am trying to get last 10 rows from file but not able to fetch.
i have two activities:
in the first, i want to write text from an EditText to a file.
in the second activity i try to read the stored data and write it to a textView
public class Date_Location extends Activity {
ImageView imageView;
EditText editTextDate, editTextLocation, editTextEdit;
private static final String TAG = Date_Location.class.getName();
private static final String FILENAME = "myFile.txt";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.date_location);
editTextDate = (EditText) findViewById(R.id.editText1);
editTextLocation = (EditText) findViewById(R.id.editText2);
editTextEdit = (EditText) findViewById(R.id.editText3);
imageView = (ImageView) findViewById(R.id.next);
}
public void goNext(View view) {
String Date = editTextDate.getText().toString();
String Location = editTextLocation.getText().toString();
String Comment = editTextEdit.getText().toString();
writeToFile(Date);
writeToFile(Location);
writeToFile(Comment);
Intent intent = new Intent(this, Detail_Data.class);
startActivity(intent);
Date_Location.this.finish();
}
private void writeToFile(String data) {
String newline = "\r\n";
try {
OutputStreamWriter oswName = new OutputStreamWriter(openFileOutput(
FILENAME, Context.MODE_APPEND));
oswName.write(newline);
oswName.write(data);
oswName.close();
} catch (IOException e) {
Log.e(TAG, "File write failed: " + e.toString());
}
}
}
And my second Activity is below
public class Detail_Data extends Activity {
TextView textView1;
ImageView imageView;
private static final String FILENAME = "myFile.txt";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.detail_data);
textView1 = (TextView) findViewById(R.id.textView1);
imageView = (ImageView) findViewById(R.id.imageView2);
String date = readFromFile();
textView1.setText(date);
}
private String readFromFile() {
String ret = "";
try {
InputStream inputStream = openFileInput(FILENAME);
ArrayList<String> bandWidth = new ArrayList<String>();
if (inputStream != null) {
InputStreamReader inputStreamReader = new InputStreamReader(
inputStream);
BufferedReader bufferedReader = new BufferedReader(
inputStreamReader);
String receiveString = "";
StringBuilder stringBuilder = new StringBuilder();
while ((receiveString = bufferedReader.readLine()) != null) {
stringBuilder.append(receiveString+'\n');
bandWidth.add(receiveString);
if (bandWidth.size() == 10)
bandWidth.remove(0);
}
ret = stringBuilder.toString();
inputStream.close();
}
} catch (FileNotFoundException e) {
Log.i("File not found", e.toString());
} catch (IOException e) {
Log.i("Can not read file:", e.toString());
}
return ret;
}
public void goNext(View view) {
imageView.setColorFilter(0xFFFF3D60, PorterDuff.Mode.MULTIPLY);
Intent intent = new Intent(this, Agreement.class);
startActivity(intent);
Detail_Data.this.finish();
}
}
please if any one have any idea then help me. I have tried with other solution too but then also i am not getting last 10 records. Instead of last 10 data i am getting all the records which is written in file.
Firstly, If you are writing file on SDcard, be sure that you have added the uses-permission tag in AndroidManifest.xml
<uses-permission Android:name="Android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>
Secondly, don't forget flush()
oswName.write(data);
oswName.flush();
oswName.close();
Then, there is something wrong with your readFromFile() method,
remove this line from while loop
stringBuilder.append(receiveString+'\n');
and add this right after the while loop
for(String str : bandWidth)
stringBuilder.append(str + "\n");
readFromFile() should be like following
private String readFromFile() {
String ret = "";
try {
InputStream inputStream = openFileInput(FILENAME);
ArrayList<String> bandWidth = new ArrayList<String>();
if (inputStream != null) {
InputStreamReader inputStreamReader = new InputStreamReader(
inputStream);
BufferedReader bufferedReader = new BufferedReader(
inputStreamReader);
String receiveString = "";
StringBuilder stringBuilder = new StringBuilder();
while ((receiveString = bufferedReader.readLine()) != null) {
bandWidth.add(receiveString);
if (bandWidth.size() == 10)
bandWidth.remove(0);
}
for(String str : bandWidth)
stringBuilder.append(str + "\n");
ret = stringBuilder.toString();
inputStream.close();
}
} catch (FileNotFoundException e) {
Log.i("File not found", e.toString());
} catch (IOException e) {
Log.i("Can not read file:", e.toString());
}
return ret;
}
After opening the input/output stream, use that methods:
import java.io.FileInputStream;
import java.io.FileOutputStream;
public class Files {
public static String readStringFile(FileInputStream fis) throws java.io.IOException {
StringBuffer fileContent = new StringBuffer("");
byte[] buffer = new byte[1024];
while (fis.read(buffer) != -1) {
fileContent.append(new String(buffer));
}
return fileContent.toString();
}
public static void writeStringFile(FileOutputStream fos, String text) throws java.io.IOException {
fos.write(text.getBytes());
}
}
First, create the FileInputStream or FileOutputStream with your desired file name and then call the methods above. Please notice that the methods only work for reading and writing strings.
You store each line to list and remove 0 position only if list size = 10
So as 1st step store all file in list:
Instead
while ((receiveString = bufferedReader.readLine()) != null) {
stringBuilder.append(receiveString+'\n');
bandWidth.add(receiveString);
if (bandWidth.size() == 10)
bandWidth.remove(0);
}
Write
while ((receiveString = bufferedReader.readLine()) != null) {
stringBuilder.append(receiveString+'\n');
bandWidth.add(receiveString);
}
After copy last 10 lines to new list.
For example if you have :
List<String> bandWidth = new ArrayList<String>(Arrays.asList("a1", "a2", "a3","a4", "a5", "a6","a7", "a8", "a9","a10", "a11", "a12"));
Than with subList:
List<String> bandWidth10rows= bandWidth.subList(bandWidth.size()-10, bandWidth.size());
It will copy last 10 list items to new list.
Totally it should be something like:
while ((receiveString = bufferedReader.readLine()) != null) {
stringBuilder.append(receiveString+'\n');
bandWidth.add(receiveString);
}
List<String> bandWidthLastTenRows= bandWidth.subList(bandWidth.size()-10, bandWidth.size());

Read previous line in a file

I have this code below that reads a next line up to the end of an unnumbered file (lines in file have no numbers) and it works perfectly fine.Now, I want to read previous lines (read backwards). If also possible, shuffle (read random lines).Any ideas.
Here is an Example:
InputStream in;
BufferedReader reader;
String qline;
try {
in = this.getAssets().open("quotations.txt");
reader = new BufferedReader(new InputStreamReader(in));
qline = reader.readLine();
quote.setText(qline);
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Inside my onClick method i have a button for next
//code
else if (v.getId() == R.id.next) {
try{
if (( qline = reader.readLine()) != null) {
// myData = myData + qline;
quote.setText(qline);
}
} catch (java.io.FileNotFoundException e) {
// do something if the myfilename.txt does not exits
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
else if (v.getId() == R.id.back) {
// code for the back option
}
You can use my library FileReader, or modify it to suit the functionality you seek:
// FileReader, Khaled A Khunaifer
public class FileReader
{
public static ArrayList<String> readAllLines (String path)
{
ArrayList<String> lines = new ArrayList<String>();
InputStream fis;
BufferedReader br;
String line;
try
{
fis = new FileInputStream(path);
br = new BufferedReader(new InputStreamReader(fis, Charset.forName("UTF-8")));
while ((line = br.readLine()) != null)
{
lines.add(line);
}
}
catch (Exception e)
{
e.printStackTrace()
}
return lines;
}
// NOTE: LINE NUMBERS START FROM 1
public static ArrayList<String> readLines (String path, long from, long to)
{
ArrayList<String> lines = new ArrayList<String>();
long k = 1;
InputStream fis;
BufferedReader br;
String line;
try
{
fis = new FileInputStream(path);
br = new BufferedReader(new InputStreamReader(fis, Charset.forName("UTF-8")));
do
{
line = br.readLine(); // read line k
if (k >= from)
{
if (k > to) break; // STOP
lines.add(line);
}
k++;
}
while (line != null);
}
catch (Exception e)
{
e.printStackTrace()
}
return line;
}
// NOTE: LINE NUMBERS START FROM 1
public static String readLine (String path, long i)
{
long k = 1;
InputStream fis;
BufferedReader br;
String line;
try
{
fis = new FileInputStream(path);
br = new BufferedReader(new InputStreamReader(fis, Charset.forName("UTF-8")));
do
{
line = br.readLine(); // read line k
if (k == i)
{
break;
}
k++;
}
while (line != null);
}
catch (Exception e)
{
e.printStackTrace()
}
return line;
}
}

read a text file android

I am trying to make the computer read a text file full of words and add it to an ArrayList. I made it work on a regular Java application, but can't get it to work on Android. Can someone help me out?
try {
FileInputStream textfl = (FileInputStream) getAssets().open("test.txt");
DataInputStream is = new DataInputStream(textfl);
BufferedReader r = new BufferedReader(new InputStreamReader(is));
String strLine;
while ((strLine = r.readLine()) != null) {
tots.add(strLine); //tots is the array list
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
I keep getting a error. The text file is 587kb, so could that be a problem?
try this.
private static String readTextFile(String fileName)
{
BufferedReader in = null;
try
{
in = new BufferedReader(new InputStreamReader(getAssets().open(fileName)));
String line;
final StringBuilder buffer = new StringBuilder();
while ((line = in.readLine()) != null)
{
buffer.append(line).append(System.getProperty("line.separator"));
}
return buffer.toString();
}
catch (final IOException e)
{
return "";
}
finally
{
try
{
in.close();
}
catch (IOException e)
{
// ignore //
}
}
}

Categories

Resources