FIleNotFoundException error was generated at runtime - android

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" />

Related

Convert input stream into file android

in my application i am using below code that returns input stream
QBContent.downloadFileById(fileId, new QBEntityCallback<InputStream>() {
#Override
public void onSuccess(final InputStream inputStream, Bundle params) {
long length = params.getLong(Consts.CONTENT_LENGTH_TAG);
Log.i(TAG, "content.length: " + length);
// use inputStream to download a file
}
#Override
public void onError(QBResponseException errors) {
}
}, new QBProgressCallback() {
#Override
public void onProgressUpdate(int progress) {
}
});
now i want to covert input steam into file then want to do two things with that file
1. how can i save it to user's phone storage
2. save it temporarily and display's it in pdf viewer using intent
note: returned file will be in pdf formal
You did not mentionned if you wanted to store in external or internal storage, I wrote this example for internal storage
BufferedReader r = new BufferedReader(new InputStreamReader(inputStream));
StringBuilder total = new StringBuilder();
String line;
while ((line = r.readLine()) != null) {
total.append(line).append('\n');
}
try {
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(context.openFileOutput("file.txt", Context.MODE_PRIVATE));
outputStreamWriter.write(total.toString());
outputStreamWriter.close();
}
catch (IOException e) {
Log.e("Exception", "File write failed: " + e.toString());
}
Don't forget to use try/catch and close what needs to be closed
You can use below code to store InputStream in File.
But you need to pass file path and where you want to store file in storage.
InputStream inputStream = null;
BufferedReader br = null;
try {
// read this file into InputStream
inputStream = new FileInputStream("/Users/mkyong/Downloads/file.js");
br = new BufferedReader(new InputStreamReader(inputStream));
StringBuilder sb = new StringBuilder();
String line;
while ((line = br.readLine()) != null) {
sb.append(line);
}
System.out.println(sb.toString());
System.out.println("\nDone!");
} catch (IOException e) {
e.printStackTrace();
} finally {
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}

java.io.FileNotFoundException for text file

I have a txt file in the root folder of my Android project called KARIN.txt. I am trying to reach it by FileReader but I am having the following error:
java.io.FileNotFoundException: /KARIN.txt: open failed: ENOENT (No such file or directory)
How I am trying to reach that file is as following:
BufferedReader br = new BufferedReader(new FileReader("KARIN.txt"));
I am confused that why it is not allowing me to read the file.
If KARIN.txt is built into your project you should put it in the assets folder and access it via the AssetManager.
public String loadFile(String file){
AssetManager am = getActivity().getAssets();
InputStreamReader ims = null;
BufferedReader reader = null;
String data = "File not available!";
try {
ims = new InputStreamReader(am.open(file), "UTF-8");
reader = new BufferedReader(ims);
} catch (IOException e) {
e.printStackTrace();
}
if(ims != null){
try {
String mLine = reader.readLine();
data = "";
while(mLine != null){
data+= mLine;
mLine = reader.readLine();
}
} catch (IOException e) {
e.printStackTrace();
} finally{
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
return data;
}

Why reading text from sd card files returns null in android?

I want to retain some strings even when i clear my app data so i am using text files saved in sd card.
I am using sd card files to store myStrings and read them at run time. but each and every time readfile return null.
following is my code:
protected void writeToFile(String data, String fileName) {
String root_sd = Environment.getExternalStorageDirectory().toString();
File dir = new File(root_sd+"/"+"AntiVirusPref");
if(dir.mkdir())
{
File f=new File( dir.getAbsolutePath()+"/"+fileName);
if (f.exists()) {
f.delete();
}
if (!f.exists()) {
try {
f.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
else {
File f=new File( dir.getAbsolutePath()+"/"+fileName);
if (f.exists()) {
f.delete();
}
if (!f.exists()) {
try {
f.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
try {
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(openFileOutput(fileName, Context.MODE_PRIVATE));
outputStreamWriter.write(data);
outputStreamWriter.close();
}
catch (IOException e) {
Log.e("Exception", "File write failed: " + e.toString());
}
}
protected String readFromFile(String fileName, String defaultValue) {
String ret = "";
String root_sd = Environment.getExternalStorageDirectory().toString();
File dir = new File(root_sd+"/"+"AntiVirusPref");
File file = new File(dir.getAbsolutePath() + "/"+fileName);
try {
//InputStream inputStream = openFileInput("/sdcard/"+fileName);
FileInputStream inputStream = new FileInputStream(file);
if ( inputStream != null ) {
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String receiveString = "";
StringBuilder stringBuilder = new StringBuilder();
/*if((receiveString = bufferedReader.read) != null){
stringBuilder.append(receiveString);
}*/
String line="";
int c;
while ((c = bufferedReader.read()) != -1) {
line+=(char)c;
//counter++;
}
stringBuilder.append(line);
inputStream.close();
ret = stringBuilder.toString();
}
}
catch (FileNotFoundException e) {
Log.e("login activity", "File not found: " + e.toString());
} catch (IOException e) {
Log.e("login activity", "Can not read file: " + e.toString());
}
if (ret.equals("")) {
ret=defaultValue;
}
return ret;
}
try to add the "file:///" suffix before the Uri

How to keep on appending logs while writing into File in SDCard?

I have written a method to print Logs in file. This is working. My only concern is that the logs are been replaced by new logs. Is there any way to keep logs appending ??
public static void printLog(Context context){
String filename = context.getExternalFilesDir(null).getPath() + File.separator + "my_app.log";
String command = "logcat -d *:V";
Log.d(TAG, "command: " + command);
try{
Process process = Runtime.getRuntime().exec(command);
BufferedReader in = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line = null;
try{
File file = new File(filename);
file.createNewFile();
FileWriter writer = new FileWriter(file);
while((line = in.readLine()) != null){
writer.write(line + "\n");
}
writer.flush();
writer.close();
}
catch(IOException e){
e.printStackTrace();
}
}
catch(IOException e){
e.printStackTrace();
}
}
Try this:
public static void printLog(String logData) {
try {
File logFile = new File(Environment.getExternalStorageDirectory(),
"yourLog.txt");
if (!logFile.exists()) {
try {
logFile.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
try {
BufferedWriter buf = new BufferedWriter(new FileWriter(logFile,
true));
buf.append(logData);
buf.newLine();
buf.close();
} catch (IOException e) {
e.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
}
}
You are not writing the file in Append mode.
Use new FileWriter(file,true) instead of new FileWriter(file)
More easy way to write to your sdcard:
try {
FileWriter f = new FileWriter(Environment.getExternalStorageDirectory()+
"/mytextfile.txt", true);
f.write("Hello World");
f.flush();
f.close();
}
The boolean in the constructor of FileWriter says its only allowed to append:
http://developer.android.com/reference/java/io/FileWriter.html#FileWriter(java.io.File, boolean)

Android: Read text file under /data/data/<package_name>/files

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;
}

Categories

Resources