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());
Related
I want to save my data in a .txt file. In another activity I want to be able to read the saved data. I want to save multible values each time and put them together on a line, the next values need to be in a new line. I tried \n System.getProperty("line.separator"); System.lineSeparator(); and \n\r to start in a new line but this doesn't seem to work while the data still end up behind each other instead of being on another line.
I use this code to write to the file:
Context context = getApplicationContext();
writedatatofile(context);
protected void writedatatofile(Context context){
try
{
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(context.openFileOutput("data_log.txt", Context.MODE_APPEND));
String data;
if (newstart){
data = "Exersice started \n" + "t.s a.s t.a a.a cnst";
} else {
data = (Integer.toString(time_step)+Integer.toString(new_average_step)+Integer.toString(time_footaid)+Integer.toString(new_average_aid)+Boolean.toString(rhythmconsistent)+"\n");
}
outputStreamWriter.append(data);
outputStreamWriter.close();
Toast.makeText(this, "Data has been written to File", Toast.LENGTH_SHORT).show();
}
catch(IOException e) {
e.printStackTrace();
}
}
and this code to read the file:
Context context = getApplicationContext();
String fileData = readFromFile(context, fileName);
TextView datalog = findViewById(R.id.datalog);
datalog.setText(fileData);
private String readFromFile(Context context, String fileName){
String ret = " ";
try {
InputStream inputStream = context.openFileInput(fileName);
if (inputStream != null) {
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String receiveString = "";
StringBuilder stringBuilder = new StringBuilder();
while ((receiveString = bufferedReader.readLine()) != null) {
Toast.makeText(this, "Data received", Toast.LENGTH_SHORT).show();
stringBuilder.append(receiveString);
}
inputStream.close();
ret = stringBuilder.toString();
} else {
Toast.makeText(this, "No data received", Toast.LENGTH_SHORT).show();
}
} catch (FileNotFoundException e){
Toast.makeText(this, "File not found", Toast.LENGTH_SHORT).show();
} catch (IOException e){
Toast.makeText(this, "Can not read file", Toast.LENGTH_SHORT).show();
}
return ret;
}
As mentioned "\n" doesn't solve the problem but is also doesn't show up in my dataas \n. So it is not stored as a normal String.
When you write the file:
BufferedWriter writer = new BufferedWriter(outputStreamWriter);
writer.write(data);
writer.newLine(); // <-- this is the magic
writer.close();
You can read the data from .txt file using below code.
File exportDir = new File(Environment.getExternalStorageDirectory(), File.separator + "bluetooth/abc.txt");
if (exportDir.exists()) {
FileReader file = null;
try {
file = new FileReader(exportDir);
BufferedReader buffer = new BufferedReader(file);
String line = "";
int iteration = 0;
while ((line = buffer.readLine()) != null) { //read next line
if (iteration == 0) { //Skip the 1st position(header)
iteration++;
continue;
}
StringBuilder sb = new StringBuilder();
String[] str = line.split(",");
//get the single data from column
String text1 = str[1].replace("\"", "");
String text2 = str[2].replace("\"", "");
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
I want to work with a text in android studio that is very long(70 pages approximately). first is a way to put in my main activity in android studio code?
OR how can I import it and use it as string?
for example:
String deey = "my long text";
so I cant use it. I want to add it to my program and use it as string.
I put it into asset folder. but I can't use it.
You can get an InputStream from the AssetManager calling the opne() method.
public static String getReadTextFromAssets(Context context, String textFileName) {
String text;
StringBuilder stringBuilder = new StringBuilder();
InputStream inputStream;
try {
inputStream = context.getAssets().open(textFileName);
BufferedReader bufferedReader =
new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
while ((text = bufferedReader.readLine()) != null) {
stringBuilder.append(text);
}
bufferedReader.close();
} catch (IOException e) {
e.printStackTrace();
}
return stringBuilder.toString();
}
Keep your file in the assets folder.
Put it in assets and read it using the below function.
public String readFromAssets(String fileName, Context context) {
StringBuilder returnString = new StringBuilder();
InputStream fIn = null;
InputStreamReader isr = null;
BufferedReader input = null;
try {
fIn = context.getResources().getAssets()
.open(fileName, Context.MODE_WORLD_READABLE);
isr = new InputStreamReader(fIn);
input = new BufferedReader(isr);
String line = "";
while ((line = input.readLine()) != null) {
returnString.append(line);
}
} catch (Exception e) {
e.getMessage();
} finally {
try {
if (isr != null)
isr.close();
if (fIn != null)
fIn.close();
if (input != null)
input.close();
} catch (Exception e2) {
e2.getMessage();
}
}
return returnString.toString();
}
So in your code you will initialise the string as
String longString = readFromAssets("helloworld.txt",mContext);
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?
}
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("$"));
I want to read several lines from a text file. These line should be displayed one by one, when I click the next button. I am able to store the strings in a file and read the first line. But when I try to read the next line using the next button, it stops working. Can anybody tell me a solution for this. Thanks in advance.
I have defined the following,
BufferedReader buffreader;
String line;
String fav;
StringBuilder text;
InputStream instream;
String favQuote0;
This is in my oncreate method
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_save);
StringBuilder text = new StringBuilder();
try {
// open the file for reading
InputStream instream = openFileInput("myfilename.txt");
// if file the available for reading
if (instream != null) {
// prepare the file for reading
InputStreamReader inputreader = new InputStreamReader(instream);
BufferedReader buffreader = new BufferedReader(inputreader);
while (( line = buffreader.readLine()) != null) {
text.append(line);
text.append('\n');
fav = text.toString();
}
}
} catch (IOException e) {}
TextView tv1 = (TextView)findViewById(R.id.textView2);
tv1.setText(fav);
}
This is my next button
public void next (View view1) {
try {
// open the file for reading
InputStream instream = openFileInput("myfilename.txt");
// if file the available for reading
if (instream != null) {
while (( line = buffreader.readLine()) != null) {
text.append(line);
text.append('\n');
fav = text.toString();
}
}
} catch (IOException e) {}
TextView tv1 = (TextView)findViewById(R.id.textView2);
tv1.setText(fav);
}
Both answers do it the wrong way. I will post a description below my code. This is the proper way of doing it.
private int mCurrentLine;
private ArrayList<String> mLines;
private TextView mTextView;
private Button mButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_save);
mCurrentLine = -1;
mLines = new ArrayList<String>();
mTextView = (TextView) findViewById(R.id.text_view);
mButton = (Button) findViewById(R.id.button);
try {
readLinesAndSaveToArrayList();
}
catch (IOException e) {
e.printStackTrace();
}
setTextAndIncrement();
mButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
setTextAndIncrement();
}
});
}
private void readLinesAndSaveToArrayList() throws IOException {
File file = new File("myfilename.txt");
if (!file.exists()) {
throw new FileNotFoundException("myfilename.txt was unable to locate");
}
FileReader fileReader = new FileReader(file);
BufferedReader bufferedReader = new BufferedReader(fileReader);
String line;
while ((line = bufferedReader.readLine()) != null) {
mLines.add(line);
}
bufferedReader.close();
}
private void setTextAndIncrement() {
if (mCurrentLine == mLines.size() - 1) {
return;
}
mCurrentLine++;
mTextView.setText(mLines.get(mCurrentLine));
}
What I do is cache the file's contents in a scalable ArrayList. Each line will be assigned to an index in the array, eg. 0, 1, 2 and so on.
mCurrentLine takes care of positioning in the array. It starts at -1 because there is no current line. In the setTextAndIncrement() it will be set to 0, which in the array is the first index (the first line). The continuous calls will increment the position and take the next lines. If you come to the limit I have put in a check that looks if the mCurrentLine is equal to the max size of lines (mLines.size() - 1, a - 1 because arrays starts from 0 instead of 1).
Other than that I would advice you to use full length names on methods and variables; there is no need to keep them short, it will only make reading them harder. XML should also only contain low letters instead of camelCases.
Try this. This i working for me
BufferedReader reader = new BufferedReader(new InputStreamReader(instream));
StringBuffer bf = new StringBuffer();
String json = reader.readLine();
try {
do {
bf.append(json);
json = reader.readLine();
}while (json != null);
wt.flush();
wt.close();
Log.d("LOG", " read line output "+new String(bf)+" json "+json);
reader.close();
} catch (Exception e) {
e.printStackTrace(); }
wt is the bufferedwriter which i used to write line. I read from reader and write into file stored locally.
try {
// open the file for reading
InputStream instream = new FileInputStream("myfilename.txt");
// if file the available for reading
if (instream != null) {
// prepare the file for reading
InputStreamReader inputreader = new InputStreamReader(instream);
BufferedReader buffreader = new BufferedReader(inputreader);
String line;
// read every line of the file into the line-variable, on line at the time
while (buffreader.hasNext()) {
line = buffreader.readLine();
// do something with the line
}
}
} catch (Exception ex) {
// print stack trace.
} finally {
// close the file.
instream.close();
}