I'm trying to read from a text file under /data/data/package_name/files.
This is my code:
private String readTxt(String fileName)
{
String result = "", line;
try
{
File f = new File(fileName);
BufferedReader br = new BufferedReader(new FileReader(f));
while((line = br.readLine()) != null)
{
result += line + "\n";
}
}
catch(Exception e)
{
e.printStackTrace();
}
return result;
}
What am I doing wrong?
You should use the openFileInput Method from your application context. http://developer.android.com/reference/android/content/Context.html#openFileInput(java.lang.String)
Which will give you a InputStream to your file
Example:
final InputStream is = getApplicationContext().openFileInput(MY_FILENAME_WITHOUT_PATH);
private String getStringFromFile(Context accessClass,String fileName){
String result=null;
FileInputStream fIn;
ContextWrapper accessClassInstance=new ContextWrapper(accessClass);
try {
fIn = accessClassInstance.openFileInput(fileName);
InputSource inputSource=new InputSource(fIn);
InputStream in = inputSource.getInputStream();
if (in != null) {
// prepare the file for reading
InputStreamReader input = new InputStreamReader(in);
BufferedReader buffreader = new BufferedReader(input);
result = "";
while (( line = buffreader.readLine()) != null) {
result += line;
}
in.close();
Toast.makeText(getApplicationContext(),"File Contents ==> " + result,Toast.LENGTH_SHORT).show();
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ParserConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SAXException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return result;
}
Related
How to get response in put method with Authentication using four Headers.In ios it works fine but not in Android.
Authentication code is generated from the data HMAC-SHA256 with the secret key provided after validation as the key
HttpPut put = new HttpPut(xAuthurl);//url
Log.v("put", "" + put);
try {
put.setEntity(new StringEntity(data, "UTF-8"));
} catch (UnsupportedEncodingException e1) {
Log.e(TAG, "UnsupportedEncoding: ", e1);
}
//Here are the four headers......
put.addHeader("Content-type", "application/json");
put.addHeader("x-Auth-user", Validation.id);//id of the profile
put.addHeader("X-Auth-Hash", hexBytes);// Hexadecimal value
put.addHeader("X-Auth-Time", sdf.format(datetime));//date format in utc
HttpResponse response = null;
try {
response = http.execute(put);
Log.v("response", "" + response.getAllHeaders());
} catch (ClientProtocolException e1) { // TODO Auto-generated catch
// block
e1.printStackTrace();
} catch (IOException e1) { // TODO
// Auto-generated catch block
e1.printStackTrace();
}
Log.d(TAG, "This is what we get back:"
+ response.getStatusLine().toString() + ", "
+ response.getEntity().toString());
try {
inputStream = response.getEntity().getContent();
} catch (IllegalStateException e1) { // TODO Auto-generated catch
// block
e1.printStackTrace();
} catch (IOException e1) { // TODO Auto-generated catch block
e1.printStackTrace();
}
if (inputStream != null) {
try {
result = convertInputStreamToString(inputStream);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Log.v("result", "" + result);
} else {
result = "Did not work!";
}
return 1;
}
private String convertInputStreamToString(InputStream inputStream)
throws IOException {
BufferedReader bufferedReader = new BufferedReader(
new InputStreamReader(inputStream));
String line = "";
String result = "";
while ((line = bufferedReader.readLine()) != null)
result += line;
inputStream.close();
return result;
}
result i get is {"Message":"An error has occurred."}
i have an text file in my assets folder called test.txt. It contains a string in the form
"item1,item2,item3
How do i read the text into and array so that I can then toast any one of the three items that are deliminated by a comma
After reading post here the way to load the file is as follows
AssetManager assetManager = getAssets();
InputStream ims = assetManager.open("test.txt");
But cant work out how to get into an array
your help is appreciated
Mark
This is one way:
InputStreat inputStream = getAssets().open("test.txt");
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
int i;
try {
i = inputStream.read();
while (i != -1)
{
byteArrayOutputStream.write(i);
i = inputStream.read();
}
inputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String[] myArray = TextUtils.split(byteArrayOutputStream.toString(), ",");
Here is a sample code :
private void readFromAsset() throws UnsupportedEncodingException {
AssetManager assetManager = getAssets();
InputStream is = null;
try {
is = assetManager.open("your_path/your_text.txt");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
BufferedReader reader = null;
reader = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));
String line = "";
try {
while ((line = reader.readLine()) != null) {
//Read line by line here
}
} catch (IOException e) {
e.printStackTrace();
}
}
private void readFileFromSDCard() {
File directory = Environment.getExternalStorageDirectory();
File file = new File(directory+"/HomeActivityLogs");
//file.getParentFile().mkdirs();
if (!file.exists()) {
FileWriter gpxwriter;
try {
System.out.println(" IN TRY Error");
file.createNewFile();
gpxwriter = new FileWriter(file);
System.out.println(" file writer Error");
BufferedWriter out = new BufferedWriter(gpxwriter);
out.write("http://192.168.1.126/msfaws2_4/Service.asmx");
System.out.println(" in url Error");
/// out.write("http://192.168.1.250/msfaws2_4/Service.asmx");
out.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
loginLog.appendLog("Exception in readFileFromSDCard() " + e.getMessage(),"MainActivity");
}
}
BufferedReader reader = null;
try {
System.out.println("Error");
reader = new BufferedReader(new FileReader(file));
StringBuilder builder = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
builder.append(line);
}
Constant.URL = builder.toString();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
loginLog.appendLog("Exception in readFileFromSDCard() " + e.getMessage(),"MainActivity");
}
}
}
}
Please help me to solve this. It gives an error filenotfound with the filename
it creates dynamically from the web services, when the data was stored temporary and then retrieved from the activity.
Try this, Add this permission in you manifest.xml
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
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 //
}
}
}
I just wanna create a text file into phone memory and have to read its content to display.Now i created a text file.But its not present in the path data/data/package-name/file name.txt & it didn't display the content on emulator.
My code is..
public class PhonememAct extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
TextView tv=(TextView)findViewById(R.id.tv);
FileOutputStream fos = null;
try {
fos = openFileOutput("Test.txt", Context.MODE_PRIVATE);
} catch (FileNotFoundException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
try {
fos.write("Hai..".getBytes());
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
fos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
FileInputStream fis = null;
try {
fis = openFileInput("Test.txt");
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
int c;
try {
while((c=fis.read())!=-1)
{
tv.setText(c);
setContentView(tv);
//k += (char)c;
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
fis.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Thanks in adv.
You don't need to use input/output streams if you are simply trying to write/read text.
Use FileWriter to write text to a file and BufferedReader to read text from a file - it's much simpler. This works perfectly...
try {
File myDir = new File(getFilesDir().getAbsolutePath());
String s = "";
FileWriter fw = new FileWriter(myDir + "/Test.txt");
fw.write("Hello World");
fw.close();
BufferedReader br = new BufferedReader(new FileReader(myDir + "/Test.txt"));
s = br.readLine();
// Set TextView text here using tv.setText(s);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
//Find the directory for the SD Card using the API
//*Don't* hardcode "/sdcard"
File sdcard = Environment.getExternalStorageDirectory();
//Get the text file
File file = new File(sdcard,"file.txt");
//Read text from file
StringBuilder text = new StringBuilder();
try {
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
while ((line = br.readLine()) != null) {
text.append(line);
text.append('\n');
}
}
catch (IOException e) {
//You'll need to add proper error handling here
}
//Find the view by its id
TextView tv = (TextView)findViewById(R.id.text_view);
//Set the text
tv.setText(text);
//To read file from internal phone memory
//get your application context:
Context context = getApplicationContext();
filePath = context.getFilesDir().getAbsolutePath();
File file = new File(filePath, fileName);
StringBuilder text = new StringBuilder();
try {
BufferedReader br = new BufferedReader(new FileReader(file));
while ((line = br.readLine()) != null) {
text.append(line);
text.append('\n');
}
}
catch (IOException e) {
}
return text.toString(); //the output text from file.
This may not be an answer to your question.
I think, you need to use the try-catch correctly.
Imagine openFileInput() call fails, and next you are calling fos.write() and fos.close() on a null object.
Same thing is seen later in fis.read() and fis.close().
You need to include openFileInput(), fos.write() and fos.close() in one single try-catch block. Similar change is required for 'fis' as well.
Try this first!
You could try it with a stream.
public static void persistAll(Context ctx, List<myObject> myObjects) {
// save data to file
FileOutputStream out = null;
try {
out = ctx.openFileOutput("file.obj",
Context.MODE_PRIVATE);
ObjectOutputStream objOut = new ObjectOutputStream(out);
objOut.writeObject(myObjects);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
It is working fine for me like this. Saving as text shouldn't be that different, but I don't have a Java IDE to test here at work.
Hope this helps!