While reading data from a stream, why does my program hang? - android

While reading data from a stream I am writing to a newly created temporary XML file. But the program hangs.
What have I missed here?
if (deviceSocket.isConnected()) {
OutputStream os = deviceSocket.getOutputStream();
os.write(xmlStr.getBytes());
os.flush();
// Read Response from Socket
respFromDevice = new BufferedReader(new InputStreamReader(deviceSocket.getInputStream()));
FileWriter fileWriter = null;
// Write into temp xml file
String response;
while ((response = respFromDevice.readLine()) != null) {
sb.append(response);
File newTextFile = new File("tmp.xml");
fileWriter = new FileWriter(newTextFile);
fileWriter.write(sb.toString());
//Files.write(Paths.get("temp.xml"), sb.toString().getBytes());
System.out.println(response);
}
}

Related

How to read logcat continuously and write into the internal storage file?

Reading logcat continuously and write into the internal storage for this i tried the below code.
public class LogCatTask extends AsyncTask<Void, String, Void> {
public AtomicBoolean run = new AtomicBoolean(true);
#Override
protected Void doInBackground(Void... params) {
try {
//create text file in SDCard
File sdCard = Environment.getExternalStorageDirectory();
File dir = new File (sdCard.getAbsolutePath() + "/myLogcat");
dir.mkdirs();
File file = new File(dir, "logcat.txt");
Runtime.getRuntime().exec("logcat -c");
Process process = Runtime.getRuntime().exec("logcat -f "+file);
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
StringBuilder log = new StringBuilder();
String line = "";
Log.e("log cat task...","while...run.get()."+run.get());
while (run.get()) {
line = bufferedReader.readLine();
//Log.e("log cat task...","while...out.");
if (line != null) {
Log.e("log cat task...","while....");
log.append(line);
//publishProgress(log.toString());
//to write logcat in text file
FileOutputStream fOut = new FileOutputStream(file);
OutputStreamWriter osw = new OutputStreamWriter(fOut);
// Write the string to the file
osw.write(log.toString());
osw.flush();
osw.close();
}
line = null;
Thread.sleep(10);
//Log.e("log cat task...","while...out.");
}
//Log.e("log cat task...","ouet....while....");
}
catch(Exception ex){
}
return null;
}
}
once the above code runs,it read the logcat and write into storage but upto some part of the log only it reads.it is not reading the continuos.How to read the logcat continuous?
Here's a working code snippet
try {
Process process = Runtime.getRuntime().exec("logcat");
BufferedReader bufferedReader = new BufferedReader(
new InputStreamReader(process.getInputStream()));
StringBuilder log=new StringBuilder();
String line = "";
while ((line = bufferedReader.readLine()) != null) {
// do what you want with the line you just read
// you're in an infinite loop continuously reading the log,
// you might want to add some mechanism to break out of it
}
}
catch (IOException e) {
fail("failed to get log");
}
Your code is overly complicated and prone to race conditions. For example, is the logcat -c guaranteed to complete before the logcat -f command. The -f command redirects output to a file, and your logic is also trying to write to that same file; that's very problematic. I've noticed that some of the logcat options such as "-T" doesn't work programmatically. Maybe the "-f" option also has problems. If you only want to read the log file up to the current time use "logcat -d".

Is it possible that a .apk file be run without Wifi?

I just used this to create a .apk file of my website. Is it possible that this file be run without accessing data connections or wifi? But all the same, the website should get updated when the Wifi or data is switched on. Anyone have anything that can help me?
First store your website's file in asset folder.
Now everytime you open the app, check if the website file exists or not to prevent app from crashing.
The code given below checks that and if it doesn't exist, then it calls a method which copies the file from asset to device storage.
File file = new File(YOUR FILE PATH);
if(!file.exists()){
//Doesn't exist. Create it in sdcard
copyAssets();
}
Here are the methods to copy the website file from asset to device storage (put them in your class) -
private void copyAssets() {
AssetManager assetManager = getAssets();
String[] files = null;
try {
files = assetManager.list("");
} catch (IOException e) {
Log.e("tag", "Failed to get asset file list.", e);
}
for(String filename : files) {
InputStream in = null;
OutputStream out = null;
try {
in = assetManager.open(filename);
File outFile = new File(DIRECTORY, filename);
out = new FileOutputStream(outFile);
copyFile(in, out);
in.close();
in = null;
out.flush();
out.close();
out = null;
} catch(IOException e) {
Log.e("tag", "Failed to copy asset file: " + filename, e);
}
}
}
private void copyFile(InputStream in, OutputStream out) throws IOException {
byte[] buffer = new byte[1024];
int read;
while((read = in.read(buffer)) != -1){
out.write(buffer, 0, read);
}
}
Then check internet connection of user (in oncreate method) -
ConnectivityManager cm =
(ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnectedOrConnecting()) {
//user is connected to internet
//put the code given ahead over here
}
Permission -
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
Now if the user is connected to the internet, access the internet and get your website's new source code like this (put this code in internet checking code given above) -
URL url = new URL(YOUR URL);
URLConnection yc = url.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(
yc.getInputStream(), "UTF-8"));
String inputLine;
StringBuilder a = new StringBuilder();
while ((inputLine = in.readLine()) != null)
a.append(inputLine);
in.close();
String source = a.toString();
Now once you have the source code, update your HTML file in device storage like this -
File gpxfile = new File(File address, "filename.html");
BufferedWriter bW;
try {
bW = new BufferedWriter(new FileWriter(gpxfile));
bW.write(source); //our new source code
bW.newLine();
bW.flush();
bW.close();
} catch (IOException e) {
e.printStackTrace();
}
You are done! Now load your file to webView from storage like this (in oncreate method after all the code that we wrote before) -
index.loadUrl("file://"+Environment.getExternalStorageDirectory()+ "Your address in storage");
It is recommended to send user requests time to time to turn on their internet to update the website and prevent use of outdated copy of it.

separate appended data from the file 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");

How to delete line in textfile android

281~name~location~#time#room%
#time2#room2%
#time3#room3;
I need to delete the second line after the % in text file. But i dont know how to do that.
BufferedReader in = null;
out = null;
File sdCard = Environment.getExternalStorageDirectory();
File root = new File (sdCard.getAbsolutePath() + "/yourFile");
try {
InputStream instream = new FileInputStream(file);
in = new BufferedReader(new InputStreamReader(instream));
out = new PrintWriter(new File(root,"yournewFile));
String line; //a line in the file
while ((line = in.readLine()) != null) {
if (!Pattern.matches("^some pattern.*",line)) { //find the line we want to delete
//if it is not the line you want to delete then write it to new file
out.println(line);
}
}
in.close();
out.flush();
out.close();
File oldFile = new File (root,"/yourFile");
oldFile.delete();
File newFile = new File (root,"/yournewFile");
newFile.renameTo(oldFile);
}catch(Exception e) {
Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_SHORT).show();
}
You should read old file and match it to the line you want to delete.if it is not the line you want to delete then write it to another file.thus you will get the new file with only that line missing which you wanted to delete.
you are done.hope it will help.

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