I am trying to do what FileWriter.println() and BufferedReader.readLine() do in Android, but in android they only allow writing it into the sdcard using those method.
I need to write some integer values into the file and then read it line by line at a later time. Some of the file operation methods I found require the length of the data read to be specified, which is not possible.
Can anyone point me to the right method? Preferably with an example of the usage...
Regards
You can write to the SD card by using this path, "\sdcard\file_name"
and read it this way,
InputStream instream = null;
as
InputStream instream = openFileInput("/sdcard/filename");
// 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
try {
while (( line = buffreader.readLine()) != null) {
Log.i(TAG, "line = "+line);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
// close the file again
try {
instream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Related
I was testing a method by which I could upload an Image available on my Android device into a BLOB field of a mySQL table. Couple of posts I ran into spoke about broader points but I was not able to tie them all up together.
Here is a part of my code. This is written in a new Thread of a service.
try {
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
builder.addTextBody(StaticVariables.filename, fileNames[i]);
//builder.addBinaryBody(StaticVariables.image, new File (getExternalCacheDir().getParent() + File.separator + StaticVariables.bills + File.separator + fileNames[i]));
builder.addTextBody(StaticVariables.image, getStringImage(Uri.fromFile(new File(getExternalCacheDir().getParent() + File.separator + StaticVariables.bills + File.separator + fileNames[i]))));
httppost.setEntity(builder.build());
HttpResponse response = httpClient.execute(httppost);
entity = response.getEntity();
String line = StaticVariables.emptyString;
InputStream instream = entity.getContent();
BufferedReader obr = new BufferedReader(new InputStreamReader(instream));
while ((line = obr.readLine()) != null) {
confirmed.add(line);
}
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
THE main issue I am facing now is that on execution, an exception is being raised where it states "413: Request Entity is too large". This occurs if I pass the file in the Binary format (the commented line of code) or the Text format.
The solution to write the images on to a folder of the server has already been done by me but I am curious to know if there is some way I could get them directly on to the DB.
Other information I should share is that I am running a very basic godaddy server and hence might not have any access to change any parameters on the server.
Let me know if you would require any other information.
Appreciate any input.
I am building an app which needs to read and edit items from a .csv file.
I can place the .csv in the assets folder but would rather the ability to search for it in the external storage as it will change regularly.
A friend has given me this code for placing it in the assets folder, but I am relatively new to android and this code doesn't make sense to me and I cant get it to work.
public ArrayList<String> Job = new ArrayList<String>();
try {
is = res.getAssets().open("Job.csv");
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
String line;
while ((line = reader.readLine()) != null)
Job.add(line);
} catch (IOException ex) {
// handle exception
} finally {
try {
is.close();
} catch (IOException e) {
// handle exception
}
}
I just want to delete 2 lines of text from a text file that I created. Currently, this is what I'm trying to get rid of the 2 lines:
private void deleteDataFromFile(String title, String Date) {
try {
//open the file
FileInputStream myIn= openFileInput(FILENAME);
//the reader given the input file stream.
InputStreamReader inputReader = new InputStreamReader(myIn);
//Aftert he inputstream is open, need also a bufferedReader
BufferedReader BR = new BufferedReader(inputReader);
//holds a line of input
String line;
//used for only erasing one date.
int counter = 0;
while ((line = BR.readLine()) != null && counter < 1) {
if (line.equals(title)) {
line.replace(title, "" + "\n");
line = BR.readLine();
line.replace(Date, "" + "\n");
counter++;
}
}
BR.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
I realize that since I'm using the replace function on a string it has no effect on the actual file itself, but I can not find any other function in the IO library to affect the text file. What I'm thinking about doing is creating a new file on the phone with the exact contents of this file and just deleting the 2 lines from it. That seems troublesome and inefficient though, and I'd like to avoid it. Any suggestions?
I am trying to get the output of android shell command 'getprop' with java since getprop() always returns null no matter what.
I tried this from developer.android.com:
Process process = null;
try {
process = new ProcessBuilder()
.command("/system/bin/getprop", "build.version")
.redirectErrorStream(true)
.start();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
InputStream in = process.getInputStream();
//String prop = in.toString();
System.out.println(in);
process.destroy();
However what is printed is not the output but a bunch of characters and numbers (dont have the exact output right now).
How can i get the output of the process?
Thanks!
Is there any particular reason why you want to run the command as an external process?
There is a simpler way:
String android_rel_version = android.os.Build.VERSION.RELEASE;
However, if you really want to do it via a shell command, here is the way I got it to work:
try {
// Run the command
Process process = Runtime.getRuntime().exec("getprop");
BufferedReader bufferedReader = new BufferedReader(
new InputStreamReader(process.getInputStream()));
// Grab the results
StringBuilder log = new StringBuilder();
String line;
while ((line = bufferedReader.readLine()) != null) {
log.append(line + "\n");
}
// Update the view
TextView tv = (TextView)findViewById(R.id.my_text_view);
tv.setText(log.toString());
} catch (IOException e) {
}
i am thinking about there are some many way to store data in file , i found one of this is useing buffedinputstream ,but i really don't know is it good ??
if i using like this , it will be most fast ??
is there any other suggestion ?? i just want make the file io more fast !!
public ArrayList<String> testReadingTxtFromFile(){
ArrayList<String> result = null;
try {
FileInputStream fIn = openFileInput("cacheingtext.txt");
InputStreamReader isr = new InputStreamReader(fIn);
BufferedReader reader = new BufferedReader(isr);
String line;
while((line = reader.readLine() )!= null){
String[] datas = line.split(",");
Log.i("check", datas.length+"");
for(String data:datas){
Log.i("check", data);
result.add(data);
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return result;
}
public void testWritingTxtToFile(String[] messages){
try {
FileOutputStream fo = openFileOutput("cacheingtext.txt", MODE_WORLD_READABLE);
OutputStreamWriter osw = new OutputStreamWriter(fo);
BufferedWriter writer = new BufferedWriter(osw);
int size = messages.length;
for(int i=0;i<size;i++){
writer.write(messages[i]);
writer.write(",");
Log.i("check", "write "+messages[i]);
}
writer.flush();
writer.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
The Reader/Writer class hierarchy is character-oriented, and the Input Stream/Output Stream class hierarchy is byte-oriented.
Basically there are two types of streams.Byte streams that are used to handle stream of bytes and character streams for handling streams of characters.
What I see in your case is that you are using a byte-oriented Stream.
Character streams are often "wrappers" for byte streams. The character stream uses the byte stream to perform the physical I/O, while the character stream handles translation between characters and bytes. FileReader, for example, uses FileInputStream, while FileWriter uses FileOutputStream.
So,if you want to generally deal with Characters (reading text files), go for Character-oriented Stream(Reader/Writer). But if you want to process the content independent of what type of file is it, go for byte-oriented stream.