I have an application consist on reading AND saving an xml file and to write it if internet connection is available,else it will read the file already saved on the terminal.
WriteFeed function:
// Method to write the feed to the File
private void WriteFeed(RSSFeed data) {
FileOutputStream fOut = null;
ObjectOutputStream osw = null;
try {
fOut = openFileOutput(fileName, MODE_PRIVATE);
osw = new ObjectOutputStream(fOut);
osw.writeObject(data);
osw.flush();
}
catch (Exception e) {
e.printStackTrace();
}
finally {
try {
fOut.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
WriteFeed function:
// Method to read the feed from the File
private RSSFeed ReadFeed(String fName) {
FileInputStream fIn = null;
ObjectInputStream isr = null;
RSSFeed _feed = null;
File feedFile = getBaseContext().getFileStreamPath(fileName);
if (!feedFile.exists())
return null;
try {
fIn = openFileInput(fName);
isr = new ObjectInputStream(fIn);
_feed = (RSSFeed) isr.readObject();
}
catch (Exception e) {
e.printStackTrace();
}
finally {
try {
fIn.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return _feed;
}
I have enough diskSpace ,sometimes i get "MemoryCach will use up to 16 Mb" ,always i get "Not enough disk space,will not index" and "FeatureCode > cannot open file"
whats wrong in my app?
Related
In my MainActivity class in onResume method I start writeFile method. The class which contains the method:
public class CacheFile {
private static final String TAG = "CacheFile";
private static final String mFileName="cachefile.txt";
private static File file;
//Write data into the file
public static void writeFile(Context context, String data) {
FileOutputStream outputStream=null;
String oldData=readFile(context)+"&"+data;
try {
file = new File(context.getCacheDir(), mFileName);
outputStream = new FileOutputStream(file);
if(data!=null) {
outputStream.write(oldData.getBytes());
}
} catch (IOException e) {
e.printStackTrace();
}finally {
if(outputStream!=null){
try{
outputStream.close();
}catch (Exception e){
e.printStackTrace();
}
}
}
}
//Read from file
public static String readFile(Context context) {
BufferedReader inputStream = null;
FileInputStream fis = null;
StringBuffer buffer = new StringBuffer();
String line;
try {
file = new File(context.getCacheDir(), mFileName);
fis=new FileInputStream(file);
inputStream = new BufferedReader(new InputStreamReader(fis));
while ((line = inputStream.readLine()) != null) {
buffer.append(line);
}
} catch (IOException e) {
e.printStackTrace();
}finally {
if(inputStream!=null){
try{
inputStream.close();
}catch (Exception e){
e.printStackTrace();
}
}
if(fis!=null){
try{
fis.close();
}catch (Exception e){
e.printStackTrace();
}
}
}
return buffer.toString();
}
public static void deleteFile(Context context){
if(file!=null){
file.delete();
}
}
}
The first I readFile and add the information for writing but when I try to read file I get FileNotFoundException in line:
fis=new FileInputStream(file) (readfile method).
Why?
This means the file really doesn't exist. Do this:
file.createNewFile();
fis = new FileInputStream(file);
// Other code
You can read about createNewFile() here. It only creates the file if it doesn't already exist.
i am trying to create a file in the internal storage, i followed the steps in android developers website but when i run the below code there is no file created
please let me know what i am missing in the code
code:
File file = new File(this.getFilesDir(), "myfile");
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
FileOutputStream fOut = null;
try {
fOut = openFileOutput("myfile",Context.MODE_PRIVATE);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
try {
fOut.write("SSDD".getBytes());
} catch (IOException e) {
e.printStackTrace();
}
try {
fOut.close();
} catch (IOException e) {
e.printStackTrace();
}
By default these files are private and are accessed by only your application and get deleted , when user delete your application
For saving file:
public void writeToFile(String data) {
try {
FileOutputStream fou = openFileOutput("data.txt", MODE_APPEND);
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(fou);
outputStreamWriter.write(data);
outputStreamWriter.close();
}
catch (IOException e) {
Log.e("Exception", "File write failed: " + e.toString());
}
}
For loading file:
public String readFromFile() {
String ret = "";
try {
InputStream inputStream = openFileInput("data.txt");
if ( inputStream != null ) {
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String receiveString = "";
StringBuilder stringBuilder = new StringBuilder();
while ( (receiveString = bufferedReader.readLine()) != null ) {
stringBuilder.append(receiveString);
}
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());
}
return ret;
}
Try to get the path for storing files were the app has been installed.The below snippet will give app folder location and add the required permission as well.
File dir = context.getExternalFilesDir(null)+"/"+"folder_name";
If you are handling files that are not intended for other apps to use, you should use a private storage directory on the external storage by calling getExternalFilesDir(). This method also takes a type argument to specify the type of subdirectory (such as DIRECTORY_MOVIES). If you don't need a specific media directory, pass null to receive the root directory of your app's private directory.
Probably, this would be the best practice.
Use this method to create folder
public static void appendLog(String text, String fileName) {
File sdCard=new File(Environment.getExternalStorageDirectory().getPath());
if(!sdCard.exists()){
sdCard.mkdirs();
}
File logFile = new File(sdCard, fileName + ".txt");
if (logFile.exists()) {
logFile.delete();
}
try {
logFile.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
try {
//BufferedWriter for performance, true to set append to file flag
BufferedWriter buf = new BufferedWriter(new FileWriter(logFile, true));
buf.write(text);
buf.newLine();
buf.close();
} catch (IOException e) {
e.printStackTrace();
}
}
In this method, you have to pass your data string as a first parameter and file name which you want to create as second parameter.
Here how I write bytes to a file. I'm using FileOutputStream
private final Handler handler = new Handler(){
#Override
public void handleMessage(Message msg) {
FragmentActivity activity = getActivity();
byte[] readBuffer = (byte[]) msg.obj;
FileOutputStream out = null;
try {
out = new FileOutputStream("myFile.xml");
out.write(readBuffer);
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
and now I want to open that file, so I need to have path of that file. So how I need to open that file?
EDIT:
Here how I read from file, but I can't see anything...
BufferedReader reader = null;
FileInputStream s = null;
try {
s = new FileInputStream("mano.xml");
reader = new BufferedReader(new InputStreamReader(s));
String line = reader.readLine();
Log.d(getTag(), line);
while (line != null) {
Log.d(getTag(), line);
line = reader.readLine();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
I recommend to use this for writting:
OutputStream out = new FileOutputStream(Environment.getExternalStorageDirectory().getAbsolutePath()+"/yourfilename");
So to read the location:
File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath()+"/"+transaction.getUniqueId()+".pdf");
To read the path:
file.getAbsolutePath();
Your file is save in path /Data/Data/Your package Name/files/myFile.xml
you can use this.getFileDir() method to get the path of the files folder on the Application.
So use this.getFileDir() + "myFile.xml" to read the file.
How it is reported inside the developers guide you have to specify where you want to save your file. You can choose between:
Saving the file in the internal storage:
String filename = "myfile";
String string = "Hello world!";
FileOutputStream outputStream;
try {
outputStream = openFileOutput(filename, Context.MODE_PRIVATE);
outputStream.write(string.getBytes());
outputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
Or on second instance you could save your file in external storage:
// Checks if external storage is available to at least read
public boolean isExternalStorageReadable() {
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state) || Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
return true;
}
return false;
}
Just remember to set permissions!!!!
Here there is the entire documentation: Documentation
I am building an articles reading android application like TechChurn. I am fetching data from server in the form of json.
I am parsing Id(unique),title, author name and articles-content from json and displaying it in list-view.
Those parsed content is stored in local for accessing without internet access.
This i have done using a cache function.
Here is my code that is using for caching -
public final class CacheThis {
private CacheThis() {
}
public static void writeObject(Context context, String fileName,
Object object) throws IOException {
FileOutputStream fos;
ObjectOutputStream oos;
if (fileExistance(fileName, context)) {
fos = context.openFileOutput(fileName, Context.MODE_PRIVATE
| Context.MODE_APPEND);
oos = new AppendingObjectOutputStream(fos);
} else {
fos = context.openFileOutput(fileName, Context.MODE_PRIVATE
| Context.MODE_APPEND);
oos = new ObjectOutputStream(fos);
}
oos.writeObject(object);
oos.flush();
oos.close();
fos.close();
}
public static List<Object> readObject(Context context, String fileName) {
List<Object> list = new ArrayList<Object>(0);
FileInputStream fis;
try {
fis = context.openFileInput(fileName);
ObjectInputStream ois = new ObjectInputStream(fis);
Object object;
try {
while (true) {
object = ois.readObject();
list.add(object);
}
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
fis.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return list;
}
public static boolean fileExistance(String fname, Context context) {
File file = context.getFileStreamPath(fname);
return file.exists();
}
}
my article should be cached based on id instead its been loaded for every-time when app is started
Use the following methods to store and retrieve the data.. Here you can store the object..
private void writeData(Object data, String fileName) {
try {
FileOutputStream fos = context.openFileOutput(fileName,
Context.MODE_PRIVATE);
ObjectOutputStream os = new ObjectOutputStream(fos);
os.writeObject(data);
os.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public Object readData(String fileName){
Object data = null;
if (context != null) {
try {
FileInputStream fis = context.openFileInput(fileName);
ObjectInputStream is = new ObjectInputStream(fis);
data = is.readObject();
is.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (StreamCorruptedException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
return data;
}
Write the data once you got the response from the server(at first request to the server). Use the id as file name. After that check for the particular file before you want to hit server for data. If the file is available then you can get the data from that file, otherwise hit the server.
public class FtpDownloadDemo {
public static void Connection(String filename) {
FTPClient client = new FTPClient();
FileOutputStream fos = null;
try {
client.connect("ftp.domain.com");
client.login("admin", "secret");
//
// The remote filename to be downloaded.
//
ftpClient.setFileType(FTP.IMAGE_FILE_TYPE);
fos = new FileOutputStream(filename);
//
// Download file from FTP server
//
client.retrieveFile("/" + filename, fos);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (fos != null) {
fos.close();
}
client.disconnect();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
I am using this code to download some image file. but at fos = new FileOutputStream(filename); getting file.jpeg is readonly file exception. i am using commons.net jar file for ftp connection. please help me where i am wrong.
I supplied the host, username and password when creating the class and then called this to download the file. Those guys were right it probably was trying to write to the root or something. I have been using commons-net-2.2.jar for this client.
public void GetFileFTP(String srcFileSpec, String destpath, String destname) {
File pathSpec = new File(destpath);
FTPClient client = new FTPClient();
BufferedOutputStream fos = null;
try {
client.connect(mhost);
client.login(muser, mpass);
client.enterLocalPassiveMode(); // important!
client.setFileType(org.apache.commons.net.ftp.FTP.BINARY_FILE_TYPE);
fos = new BufferedOutputStream(
new FileOutputStream(pathSpec.toString()+"/"+destname));
client.retrieveFile(srcFileSpec, fos);
}//try
catch (IOException e) {
Log.e("FTP", "Error Getting File");
e.printStackTrace();
}//catch
finally {
try {
if (fos != null) fos.close();
client.disconnect();
}//try
catch (IOException e) {
Log.e("FTP", "Disconnect Error");
e.printStackTrace();
}//catch
}//finally
Log.v("FTP", "Done");
}//getfileFTP
Hope this helps.
phavens