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.
Related
I want to use a Class method to read a text file & pass a return value.
My error is the line:
fis = openFileInput(FILE_NAME);
The error message is:
Cannot resolve method 'openFileInput(java.lang.String)'
I suspect it's because I'm not passing a context, or that Android does not know the full file path using my Class method code.
I want to use the Class method so I can call it from various Activities.
import java.io.FileInputStream;
public static String GetUserId(){
String str_return = null;
String FILE_NAME = "userid.txt";
try {
FileInputStream fis = null;
fis = openFileInput(FILE_NAME); \\<-- error is here
InputStreamReader isr = new InputStreamReader(fis);
BufferedReader br = new BufferedReader(isr);
StringBuilder sb = new StringBuilder();
String text;
while ((text = br.readLine()) != null) {
sb.append(text).append("\n");
}
} catch (FileNotFoundException e) {
//e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fis != null) {
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
try this :
File yourFile = new File("YOUR_TEXTFILE_PATH");
String data = null;
try (FileInputStream stream = new FileInputStream(yourFile)) {
FileChannel fc = stream.getChannel();
MappedByteBuffer bb = fc.map(FileChannel.MapMode.READ_ONLY, 0, fc.size());
data = Charset.defaultCharset().decode(bb).toString(); //this is the data from your textfile
} catch (Exception e) {
e.printStackTrace();
}
And generating the textfile
File root = new File("YOUR_FOLDER_PATH");
//File root = new File(Environment.getExternalStorageDirectory(), folderName); //im using this
//creation of folder (if you want)
if (!root.exists()) {
root.mkdirs();
}
File gpxfile = new File(root, textFileName);
FileWriter writer;
writer = new FileWriter(gpxfile);
writer.append(textFileData);
writer.flush();
writer.close();
}
I have done it in one of my kotlin project likethis, It might work in Java too.
val textFromFile = openFileInput(filePath).reader().readText()
I've created Test.txt on sdcard and write string "test example" on it.
after that, I replace string "test" by "etc" in Test.txt.
this is my code :
String origin_str, old_str , new_str;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_t2);
origin_str = "test example";
old_str = "test";
new_str = "etc";
Button bt_create2 = (Button)findViewById(R.id.bt_createfileT2);
bt_create2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
File newFolder = new File(Environment.getExternalStorageDirectory(), "TestFolder");
if (!newFolder.exists()) {
newFolder.mkdir();
}
File file = new File(newFolder, "Test" + ".txt");
if (!file.exists()) {
file.createNewFile();
FileOutputStream fOut = new FileOutputStream(file);
OutputStreamWriter myOutWriter =new OutputStreamWriter(fOut);
myOutWriter.append(origin_str);
myOutWriter.close();
fOut.close();
}
} catch (Exception e) {
System.out.println("e: " + e);
}
}
});
Button bt_replacefileT2 = (Button)findViewById(R.id.bt_replacefileT2);
bt_replacefileT2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
File file = new File(Environment.getExternalStorageDirectory() + "/TestFolder/Test.txt");
FileInputStream in = new FileInputStream(file);
int len = 0;
byte[] data1 = new byte[1024];
while ( -1 != (len = in.read(data1)) ){
if(new String(data1, 0, len).contains(old_str)){
String s = "";
s = s.replace(old_str, new_str);
}
}
}
catch (Exception e){
e.printStackTrace();
}
}
});
with this code, it was create Test.txt on sdcard and write "test example" on it.
but when replace string "test" by "etc", it not working.
how to fix it?
I will give my code, always worked for me :)
Hope thi can help you :DD
public void saveString(String text){
if(this.isExternalStorageAvailable()){
if(!this.isExternalStorageReadOnly()){
try {
FileOutputStream fos = new FileOutputStream(
new File(this.getExternalFilesDir("text"), "text.dat"));
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeBytes(text);
oos.close();
fos.close();
} catch (FileNotFoundException e) {
//Toast.makeText(main, "Eror opening file", Toast.LENGTH_SHORT).show();
} catch (IOException e) {
//Toast.makeText(main, "Eror saving String", Toast.LENGTH_SHORT).show();
}
}
}
}
private static boolean isExternalStorageAvailable(){
String estadoSD = Environment.getExternalStorageState();
if(Environment.MEDIA_MOUNTED.equals(estadoSD))
return true;
return false;
}
private static boolean isExternalStorageReadOnly(){
String estadoSD = Environment.getExternalStorageState();
if(Environment.MEDIA_MOUNTED_READ_ONLY.equals(estadoSD))
return true;
return false;
}
public String getString(){
FileInputStream fis = null;
ObjectInputStream ois = null;
if(this.isExternalStorageAvailable()) {
try {
fis = new FileInputStream(
new File(this.getExternalFilesDir("text"), "text.dat"));
ois = new ObjectInputStream(fis);
String text = (String)ois.readObject();
return familia;
} catch (FileNotFoundException e) {
//Toast.makeText(main, "The file text doesnt exist", Toast.LENGTH_SHORT).show();
} catch (StreamCorruptedException e) {
//Toast.makeText(main, "Eror opening file", Toast.LENGTH_SHORT).show();
} catch(EOFException e){
try {
if(ois != null)
ois.close();
if(fis != null)
fis.close();
} catch (IOException e1) {
e1.printStackTrace();
}
} catch (IOException e) {
//Toast.makeText(main, "eror reading file", Toast.LENGTH_SHORT).show();
} catch (ClassNotFoundException e) {
//Toast.makeText(main, "String class doesnt exist", Toast.LENGTH_SHORT).show();
}
}
return null;
}
try this
File file = new File(Environment.getExternalStorageDirectory() + "/TestFolder/Test.txt");
try {
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
while ((line = br.readLine()) != null) {
line = line.replace(old,new);
}
br.close();
FileOutputStream fOut = new FileOutputStream(file);
OutputStreamWriter myOutWriter =new OutputStreamWriter(fOut);
myOutWriter.write(line);
myOutWriter.close();
fOut.close();
}
catch (IOException e) {
//You'll need to add proper error handling here
}
I have succesfully saved int values to sd but cant read. It always gives numberformat information. I made all logics, but cant find why it gives error.
Here is my code ;
this my constant
private final static String EXTERNAL_FILES_DIR = "ARDROID";
private final static String FILE_NAME = "turkcell.txt";
private boolean isThereAnySavedFile = false;
when this method called, it tries to open file, if file does not exist, create the file
public void anySavedDataInSD() {
String textFromSD = String.valueOf(read());
if (isThereAnySavedFile) {
int numberOfSendedSMS = Integer.parseInt(textFromSD.toString());
numberOfSendedSMS++;
writeToSD(String.valueOf(numberOfSendedSMS));
} else {
int first=60;
String g = String.valueOf(first);
writeToSD(g);
}
}
this method for writing
private void write(File file, String msg) {
FileOutputStream outputStream = null;
try {
outputStream = new FileOutputStream(file);
outputStream.write(msg.getBytes());
Logger.info("oldu bu kez");
} catch (IOException e) {
Logger.info("oldu bu kez2" + e);
} finally {
Logger.info("oldu bu kez3");
try {
if (outputStream != null)
outputStream.close();
} catch (IOException exception) {
}
}
}
this methof for reading
public StringBuilder read() {
StringBuilder textBuilder = new StringBuilder();
BufferedReader reader = null;
try {
File externalFilesDir = getExternalFilesDir(EXTERNAL_FILES_DIR);
File file = new File(externalFilesDir, FILE_NAME);
Logger.info("oldu2");
reader = new BufferedReader(new FileReader(file));
String line;
while ((line = reader.readLine()) != null) {
textBuilder.append(line);
textBuilder.append("\n");
}
isThereAnySavedFile = true;
} catch (FileNotFoundException e) {
Logger.info("oldu3");
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return textBuilder;
}
I am downloading a json response array string from network and displaying a listview using this data.I want to store this response for first time in a file stored under internal/external storage, so i dont have to download the data again in future.
How can i store this response in a internal/external storage file and read it later when my application starts afresh again.And File should be created first time only and later when application is started again, a check to whether file exists or not should be in place.
Any examples /utility class where this has been done?
Here is my code...
The Problem with this code is...it always creates a new directory and a new file.
public class FileCache {
static File cacheDir;
static final String DIRECTORY_ADDRESS = "/Android/data/com.example.savefiletostoragedemo/.newDirectory";
static final String TAG="DEMO";
public static void createDirectory(Context context){
Log.i(TAG,"createDirectory() called...");
if (android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED)){
cacheDir = new File(Environment.getExternalStorageDirectory(),DIRECTORY_ADDRESS);
Log.i(TAG,"cacheDir exists in ext storage?: "+cacheDir.exists());
}
else{
cacheDir=context.getCacheDir();
Log.i(TAG,"cacheDir exists in int storage?: "+cacheDir.exists());
}
if(!cacheDir.exists()){
cacheDir.mkdirs();
Log.i(TAG,"A New Directory is made[ "+cacheDir.getAbsolutePath());
}
else{
Log.i(TAG,"Cache Dir already exists[ "+cacheDir.getAbsolutePath());
}
}
public static File getFile(String filename){
//String filename=String.valueOf(url.hashCode());
File f = new File(cacheDir, filename);
return f;
}
public static void saveFile(String dataToWrite, File file){
try {
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(new FileOutputStream(file));
outputStreamWriter.write(dataToWrite);
outputStreamWriter.close();
} catch (FileNotFoundException e) {
} catch (IOException e) {
}
}
public static String readFromFile(File file){
try{
InputStreamReader inputStreamReader = new InputStreamReader(new FileInputStream(file));
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String receiveString = "";
StringBuilder stringBuilder = new StringBuilder();
while ( (receiveString = bufferedReader.readLine()) != null ) {
stringBuilder.append(receiveString);
}
bufferedReader.close();
inputStreamReader.close();
return stringBuilder.toString();
}
catch (FileNotFoundException e) {
} catch (IOException e) {
}
return null;
}
public static void clear(){
File[] files=cacheDir.listFiles();
if(files==null)
return;
for(File f:files)
f.delete();
}
}
I call createDirectory() in Application class
MainActivity.Java
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new DownloadUrsl().execute(null,null,null);
}
private class DownloadUrsl extends AsyncTask<String,String,String>{
#Override
protected String doInBackground(String... arg0) {
File f = getJson("LISTVIEWDATA");
//String jsonString =FileCache.readFromFile(f);
//Log.i("DEMO", "DATA Read from file is:[ "+jsonString+" ]")
return null;
}
private File getJson(String filename) {
File f = FileCache.getFile(filename);
if(f != null && f.isFile()) {
String jsonString =FileCache.readFromFile(f);
Log.i("DEMO", "DATA Read from file is:[ "+jsonString+" ]");
return f;
}
try {
Log.i("DEMO", "Starting data download...");
HttpClient httpclient = new DefaultHttpClient();
// make GET request to the given URL
URI uri = new URI("");
HttpResponse httpResponse = httpclient.execute(new HttpGet(uri));
String response =EntityUtils.toString(httpResponse.getEntity());
Log.i("DEMO", "DATA Received from net is:[ "+response+" ]");
JSONArray array=new JSONArray(response);
FileCache.saveFile(array.toString(), f);
return f;
} catch (Exception ex) {
return null;
}
}
}
Issues with this Code: This code always creates a new directory when application starts...And also creates a new file everytime the data is requested.I also tried isDirectory(), didnt work.
here is how i did it.. Thank you guys For Your Help..:)
public static void createDirectory(Context context){
Log.i(TAG,"createDirectory() called...");
if (android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED)){
File dataDir = new File(new File(Environment.getExternalStorageDirectory(), "Android"), "data");
cacheDir = new File(new File(dataDir, context.getPackageName()), "cache");
Log.i(TAG,"cacheDir exists in ext storage?: "+cacheDir.isDirectory());
}
else{
cacheDir=context.getCacheDir();
Log.i(TAG,"cacheDir exists in int storage?: "+cacheDir.isDirectory());
}
if(!cacheDir.isDirectory()){
cacheDir.mkdirs();
Log.i(TAG,"A New Directory is made[ "+cacheDir.getAbsolutePath());
}
else{
Log.i(TAG,"Cache Dir already exists[ "+cacheDir.getAbsolutePath());
}
}
public static File getFile(String filename){
//String filename=String.valueOf(url.hashCode());
File f = new File(cacheDir, String.valueOf(filename.hashCode()));
return f;
}
public static void saveFile(String dataToWrite, File file){
try {
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(new FileOutputStream(file));
outputStreamWriter.write(dataToWrite);
outputStreamWriter.close();
} catch (FileNotFoundException e) {
} catch (IOException e) {
}
}
public static String readFromFile(File file){
try{
InputStreamReader inputStreamReader = new InputStreamReader(new FileInputStream(file));
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String receiveString = "";
StringBuilder stringBuilder = new StringBuilder();
while ( (receiveString = bufferedReader.readLine()) != null ) {
stringBuilder.append(receiveString);
}
bufferedReader.close();
inputStreamReader.close();
return stringBuilder.toString();
}
catch (FileNotFoundException e) {
} catch (IOException e) {
}
return null;
}
private static final String cacheDir = Environment.getExternalStorageDirectory().getAbsolutePath() + "/Android/data/" + MyUtilClass.class.getPackage().getName();
public static void cacheResponse(String name, List<String> data) throws IOException {
File f = new File(cacheDir + "/" + name);
if (f.exists())
return;
Writer fw = new FileWriter(f);
for (String line : data) {
fw.write(line);
}
fw.close();
}
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?