separate appended data from the file android - android

I am writing data in file continuously in append mode using FileOutputStream. Everything is working fine but I want to separate each appended stream from file while reading it.
Here is how I created file and writing it in Android
FileOutputStream outputStream = service.openFileOutput("text.txt", Context.MODE_APPEND);
outputStream.write(measurement.toString().getBytes());
outputStream.close();
It is appending data successfully but when I am reading it I do not know how to find end point between appended strings.
Here is my code to read the string from file
StringBuilder total = new StringBuilder();
FileInputStream inputStream = service.openFileInput("text.txt");
BufferedReader r = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = r.readLine()) != null) {
total.append(line);
}
r.close();
inputStream.close();
Log.d(TAG, "File Size: "+total.length());

For future references, it is silly that I have not tried but thanks to #greenapps
I just had to add another write statement to append
FileOutputStream outputStream = service.openFileOutput("text.txt", Context.MODE_APPEND);
outputStream.write(measurement.toString().getBytes());
outputStream.write("\n".getBytes());
outputStream.close();
for reading saparated string I simply used split for java
String[] parts = total.toString().split("\n");
for(int i = 0; i < parts.length; i++) {
Log.d(TAG, parts[i]);
}
deleteFile("text.txt");

Related

Async Socket Server Listen Again

I am using the sample from Microsoft's Async Socket Listener. I got everything working fine, I am able to send files and data etc. However, I am struggling with trying to keep the socket open. I do not want to close the socket and re-open for every file I am sending. I want to keep it open until all files are sent. I assume the issue is in the 'SendCallback' but I can not seem to get it to work.
.Net Code
Private Shared Sub SendCallback(ar As IAsyncResult)
Try
' Retrieve the socket from the state object.
Dim handler As Socket = DirectCast(ar.AsyncState, Socket)
' Complete sending the data to the remote device.
Dim bytesSent As Integer = handler.EndSend(ar)
'trying to receive again - I added this after commenting out the below lines but am missing something.
Dim state As StateObject = DirectCast(ar.AsyncState, StateObject)
handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, New AsyncCallback(AddressOf ReadCallback), state)
'The below lines are what was there, I tried to comment out and use the above lines trying to receive again but it does not work. I assume I am missing something simple but can not find anything useful. Any help would be appreciated.
'handler.Shutdown(SocketShutdown.Both)
'handler.Close()
Catch e As Exception
PubVars.ServerStatus = e.ToString
End Try
End Sub
I know I do not want to close the socket until all is sent but I am not sure what i am missing. I want to send the first file, then send back to the client a status update which all works well. Then when the client receives the status update, I want to send the next file and so on.
Android Code:
Socket socket = null;
try {
socket = new Socket("localhost", 11000);
OutputStream out = socket.getOutputStream();
PrintWriter output = new PrintWriter(out);
String FileName = "my.jpg";
String FilePath= Environment.getExternalStorageDirectory() + "/mydir/" + FileName;
File f= new File(FilePath);
byte[] data= readFileToByteArray(f);
String strbase64 = Base64.encodeToString(data, Base64.DEFAULT);
//I chose to pass the filename as part of my header string then parse it out on server
output.println("<HEADER>" + FileName + "</HEADER>" + strbase64 + "<EOF>");
output.flush();
InputStream in = socket.getInputStream();
BufferedReader r = new BufferedReader(new InputStreamReader(in));
StringBuilder returnString = new StringBuilder();
String line;
while ((line = r.readLine()) != null) {
returnString.append(line).append('\n');
}
Log.i("INPUT",returnString.toString());
//If true run the next one
//SEND NEW FILE
Log.i("NEXT","STARTING NEXT FILE");
FileName = "my2.png";
FilePath= Environment.getExternalStorageDirectory() + "/mydir/" + FileName;
f= new File(FilePath);
data= readFileToByteArray(f);
strbase64 = Base64.encodeToString(data, Base64.DEFAULT);
output.println("<HEADER>" + FileName + "</HEADER>" + strbase64 + "<EOF>");
output.flush();
in = socket.getInputStream();
r = new BufferedReader(new InputStreamReader(in));
returnString = new StringBuilder();
while ((line = r.readLine()) != null) {
returnString.append(line).append('\n');
}
Log.i("INPUT",returnString.toString());
//END ANOTHER FILE
output.close();
in.close();
socket.close();
} catch (IOException e) {
e.printStackTrace();
}

Issues in reading of data from text file Android Development

i have been experiencing problem reading data from text files which resides in my internal storage of my mobile phone. My code is as below:
public void recommend(View view) {
Context context = getApplicationContext();
String filename = "SendLog.txt";
TextView tv = (TextView)findViewById(R.id.textView134);
try {
FileInputStream fis = context.openFileInput(filename);
InputStreamReader isr = new InputStreamReader(fis, "UTF-8");
BufferedReader bufferedReader = new BufferedReader(isr);
StringBuilder sb = new StringBuilder();
String line;
while ((line = bufferedReader.readLine()) != null) {
sb.append(line).append("\n");
tv.getText();
tv.setText(line);
}
} catch (IOException e) {
e.getStackTrace();
}
I'm not getting any data input to my mobile phone. My "SendLog.txt" file reside in /storage/emulated/0/SendLog.txt directory. Anyone can assist me? I want to read everything from the text file and display in textView134. Anyone can assist?
Thank you in advance!
"/storage/emulated/0/SendLog.txt" is located on the External Storage, not the internal.
Instead of context.openFileInput(filename) you should be using Environment.getExtenalStorageDirectory() for example,
FileInputStream fis = new FileInputStream(new File(Environment.getExtenalStorageDirectory(), filename));
Though you will need to handle possibilities such as the External Storage being unavailable / unmounted.
You will also need the manifest permission to read external storage, or alternately to write it if you plan to do that as well (you only need one of the two, as write implies read).
You are building a string using stringbuilder but instead are settexting line. The result is last line in file, which may be an empty line

Storing txt files

I'm working on a sort of a magazine app which contains a lot of txt files which I read the text from (only read not write) , And I'm a little bit confused , I have read the documentation about file storage but still don't seem to get the right way to store my txt files. Should those files be in the the Assets? Is it possible to have a folders inside the assets? And if yes how can I acsses these folders?
res/raw will be a good place to put them. If you placed a text file named "article.txt" in the raw resource folder, you would start by putting the file into an InputStream like this (note that "ctx" is a Context which an Activity inherits from):
InputStream inputStream = ctx.getResources().openRawResource(R.raw.article);
Then you turn the InputStream into a String. This can be done about 1000 different ways. Here's one way:
InputStreamReader inputreader = new InputStreamReader(inputStream);
BufferedReader buffreader = new BufferedReader(inputreader);
String line;
StringBuilder text = new StringBuilder();
try {
while (( line = buffreader.readLine()) != null) {
text.append(line);
text.append('\n');
}
} catch (IOException e) {
return null;
}
String fileContentsStr = text.toString();
Here is a fully working method (using the above conversion technique) to turn a text file from the raw folder into a string. Which I got from this post Android read text raw resource file.
public static String readRawTextFile(Context ctx, int resId)
{
InputStream inputStream = ctx.getResources().openRawResource(resId);
InputStreamReader inputreader = new InputStreamReader(inputStream);
BufferedReader buffreader = new BufferedReader(inputreader);
String line;
StringBuilder text = new StringBuilder();
try {
while (( line = buffreader.readLine()) != null) {
text.append(line);
text.append('\n');
}
} catch (IOException e) {
return null;
}
return text.toString();
}
Using "article.txt" still, you would call this method from an Activity like so:
readRawTextFile(this, R.raw.article);

Reading specific part from txt file is not working

This is my code:
File root = Environment.getExternalStorageDirectory();
File dir = new File (root.getAbsolutePath() + "/Bonbon info");
dir.mkdirs();
File f = new File(dir, "paket.txt");
StringBuilder text = new StringBuilder();
try {
BufferedReader br = new BufferedReader(new FileReader(f));
String line;
br.skip(60);
int charactersRead = 0;
while ((line = br.readLine()) != null && charactersRead < 12) {
text.append(line);
text.append('\n');
charactersRead++;
}
}
catch (IOException e) {
}
final String URL = text.toString();
TextView tv = (TextView)findViewById(R.id.textView2);
tv.setText(text);
Reading is working, but i can't read only 12 characters, it reads trough the end of file, don't know why.
I'm guessing your file is relatively short.
You're calling BufferedReader.readLine(), which in an attempt to be efficient is sucking up a big chunk of the file stream rather than going through it character-by-character.
If you want that finer control over what you read, it's probably worth using an InputStream implementation straight up.

Problems reading text from file

I'm trying to read some text from a .txt file, here's my code:
String filePath = bundle.getString("filepath");
StringBuilder st = new StringBuilder();
try {
File sd = Environment.getExternalStorageDirectory();
File f = new File(sd, filePath);
FileInputStream fileis = new FileInputStream(f);
BufferedReader buf = new BufferedReader(new InputStreamReader(
fileis));
String line = new String();
while ((line = buf.readLine()) != null) {
st.append(line);
st.append('\n');
}
Log.i("egor", "reading finished, line is " + line);
} catch (FileNotFoundException e) {
Log.i("egor", "file not found");
} catch (IOException e) {
Log.i("egor", "io exception");
}
reader.setText(st.toString());
The text looks like this:
This is a sample text to test
The .txt file is created in Windows notepad.
And here's what I'm getting:
What's wrong with my code? Thanks in advance.
Is the file in utf-8 (unicode) format? For some reason, Notepad always adds a byte-order mark to unicode files, even when the byte-order is irrelevant. When interpreted as ASCII or ANSI, the BOM will be seen as several characters. It's possible this is what's causing your problem.
If so, the solution is to use a more competent text editor than Notepad, or write code that checks for a BOM first in all unicode files.
If none of this makes sense to you, try googling 'unicode' and 'byte-order mark'.
Wrap a FileReader object in the BufferedReader object instead.
http://download.oracle.com/javase/1.4.2/docs/api/java/io/FileReader.html
File sd = Environment.getExternalStorageDirectory();
File file = new File(sd, filePath);
BufferedReader br = new BufferedReader(new FileReader(file));
String line = "";
while ((line = br.readLine()) != null) {
st.append(line);
st.append("\n");
}
br.close();
Try with the folowing code
File f = new File(str);
FileInputStream fis = new FileInputStream(f);
byte[] mydata1 = new byte[(int) f.length()];
fis.read(mydata1);
System.out.println("...data present in 11file..."+new String(mydata1));

Categories

Resources