This is what doing to read from a .txt file in my android activity. Though the app runs, I find that no file is created/appended. In logcat following line is shown,
java.io.FileNotFoundException: /home/Desktop/RiaC_android/Test/app/src/main/assets/SampleFile.txt: open failed: ENOENT (No such file or directory)
The code I'm currently using, though I have tried before,
BufferedWriter out = new BufferedWriter(
new FileWriter("test_File.txt"));
however, the result remains same.
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.widget.TextView;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
public class MainActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView tv = (TextView)findViewById(R.id.textView);
File testFile = new File("/home/Desktop/RiaC_android/Test/app/src/main/assets", "SampleFile.txt");
FileWriter writer = null;
try {
writer = new FileWriter(testFile, true);
writer.write("Hello File!!");
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
if (testFile.exists())
tv.setText("File created!!");
}
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
}
Any suggestions about what I'm doing wrong?
You can't write file to assets folder.The assets folder is read-only at runtime. Pick a different location to save your data. ie , Environment.getExternalStorageDirectory() don't use Environment.getExternalStorageDirectory().getAbsolutePath().
For reading files from asset use the following method
public String readFromAsset(String fileName, Context context) {
StringBuilder returnString = new StringBuilder();
InputStream fIn = null;
InputStreamReader isr = null;
BufferedReader input = null;
try {
fIn = context.getResources().getAssets()
.open(fileName, Context.MODE_WORLD_READABLE);
isr = new InputStreamReader(fIn);
input = new BufferedReader(isr);
String line = "";
while ((line = input.readLine()) != null) {
returnString.append(line);
}
} catch (Exception e) {
e.getMessage();
} finally {
try {
if (isr != null)
isr.close();
if (fIn != null)
fIn.close();
if (input != null)
input.close();
} catch (Exception e2) {
e2.getMessage();
}
}
return returnString.toString();
}
You can't write to /asset directory because it is read-only.
The assets folder is like folders res, src, gen, etc. These are all useful to provide different files as input to build system to generate APK file for your app.
All these are read-only while your app is running. At run-time you can write to SD card.
You do not access assets/ at runtime using File. You access assets/ at runtime using AssetManager, which you can get via getResources().getAssets().
To read from /asset folder, use the following code:
AssetManager assetManager = getResources().getAssets();
InputStream inputStream = null;
try {
inputStream = assetManager.open("SampleFile.txt");
if ( inputStream != null)
Log.d("TAG", "It worked!");
} catch (Exception e) {
e.printStackTrace();
}
You cannot modify files in asset folder. just think them readonly files.
If you want to create text file and modify them, create a file using getExternalCacheDir and new File method.
public static File CreateTextFile(Context context, String filename) throws IOException {
final File root = context.getExternalCacheDir();
return new File(root, filename);
}
EDIT APPENDED BELOW
1. To write text simply, do as below
String text = "bla bla";
FileWriter writer=null;
try {
File file = CreateTextFile("something.txt"); // proposed method
if(!file.exists())
file.createNewFile();
writer = new FileWriter(file);
/** Saving the contents to the file*/
writer.write(text);
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
2. To read cache file,
Check this link: https://stackoverflow.com/a/5971667/361100
3. One more example
Below example is to write fetched text from internet.
String webUrl = "http://www.yourdata.com/data.txt";
try {
URL url = new URL(webUrl);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setDoInput(true);
urlConnection.connect();
File file = CreateTextFile("something.txt"); // proposed method
if(!file.exists())
file.createNewFile();
FileOutputStream fileOutput = new FileOutputStream(file);
InputStream inputStream = urlConnection.getInputStream();
int totalSize = urlConnection.getContentLength();
int downloadedSize = 0;
byte[] buffer = new byte[1024];
int bufferLength = 0;
while ( (bufferLength = inputStream.read(buffer)) > 0 ) {
fileOutput.write(buffer, 0, bufferLength);
downloadedSize += bufferLength;
Log.i("Progress:","downloadedSize:"+downloadedSize+"totalSize:"+ totalSize) ;
}
fileOutput.close();
if(downloadedSize==totalSize)
filepath=file.getPath();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
filepath=null;
}
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 have a resource file in my /res/raw/ folder (/res/raw/textfile.txt) which I am trying to read from my android app for processing.
public static void main(String[] args) {
File file = new File("res/raw/textfile.txt");
FileInputStream fis = null;
BufferedInputStream bis = null;
DataInputStream dis = null;
try {
fis = new FileInputStream(file);
bis = new BufferedInputStream(fis);
dis = new DataInputStream(bis);
while (dis.available() != 0) {
// Do something with file
Log.d("GAME", dis.readLine());
}
fis.close();
bis.close();
dis.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
I have tried different path syntax but always get a java.io.FileNotFoundException error. How can I access /res/raw/textfile.txt for processing? Is File file = new File("res/raw/textfile.txt"); the wrong method in Android?
***** Answer: *****
// Call the LoadText method and pass it the resourceId
LoadText(R.raw.textfile);
public void LoadText(int resourceId) {
// The InputStream opens the resourceId and sends it to the buffer
InputStream is = this.getResources().openRawResource(resourceId);
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String readLine = null;
try {
// While the BufferedReader readLine is not null
while ((readLine = br.readLine()) != null) {
Log.d("TEXT", readLine);
}
// Close the InputStream and BufferedReader
is.close();
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
Note this will return nothing, but will print the contents line by line as a DEBUG string in the log.
If you have a file in res/raw/textfile.txt from your Activity/Widget call:
getResources().openRawResource(...) returns an InputStream
The dots should actually be an integer found in R.raw... corresponding to your filename, possibly R.raw.textfile (it's usually the name of the file without extension)
new BufferedInputStream(getResources().openRawResource(...)); then read the content of the file as a stream
I'm running an Android application and I want to load a font dynamically and use it during runtime. How can I do this?
And also how can I include a font in an SDK that I've written, reference the sdk in the app I've written, and use the font included in the SDK?
Edit: Thanks for putting a -1 Vote on this, whoever did this, I'll stop sharing knowledge, that's a good way to shut me down.
Here's how I would do it: (Using an AsyncTask, which is not perfect)
If you want something more stable than an AsyncTask RxAndroid offers other good variants, far more stable.
In this example I'm doing everything in the "doInBackground" section, but you can use it the same way, anywhere after the task is done.
This example also assumes we have persmissions to write and read from external storage.
private class DownloadTask extends AsyncTask<String, Integer, String> {
private Context context;
public DownloadTask(Context context) {
this.context = context;
}
#Override
protected String doInBackground(String... sUrl) {
InputStream input = null;
OutputStream output = null;
HttpURLConnection connection = null;
try {
URL url = new URL(sUrl[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
// expect HTTP 200 OK, so we don't mistakenly save error report
// instead of the file
if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
return "Server returned HTTP " + connection.getResponseCode()
+ " " + connection.getResponseMessage();
}
// download the file
input = connection.getInputStream();
File sdCard = Environment.getExternalStorageDirectory();
File dir = new File (sdCard.getAbsolutePath() + "/fonts");
dir.mkdirs();
File file = new File(dir, "font.ttf");
try {
OutputStream out = new FileOutputStream(file);
byte[] buf = new byte[1024];
int len;
while((len=input.read(buf))>0){
out.write(buf,0,len);
}
out.close();
input.close();
} catch (Exception e) {
e.printStackTrace();
}
File sdcard = Environment.getExternalStorageDirectory();
File dirs = new File(sdcard.getAbsolutePath()+"/fonts");
if(dirs.exists()) {
File[] files = dirs.listFiles();
Log.d("s","files");
}
final Typeface typeface = Typeface.createFromFile(
new File(Environment.getExternalStorageDirectory()+"/fonts", "font.ttf"));
Log.d("a","created");
// Now I'm starting with an example that shows how to use
// this font on a textview of my choice.
// Assumptions: font has characters uF102 and uF104
final TextView tv = (TextView) findViewById(R.id.myTextView);
runOnUiThread(new Runnable() {
#Override
public void run() {
if (tv != null && typeface != null) {
tv.setTypeface(typeface);
tv.setText("\uF102");
tv.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (tv.getText().equals("\uF102")){
tv.setText("\uF104");
} else {
tv.setText("\uF102");
}
}
});
}
}
});
} catch (Exception e) {
return e.toString();
} finally {
try {
if (output != null)
output.close();
if (input != null)
input.close();
} catch (IOException ignored) {
}
if (connection != null)
connection.disconnect();
}
return null;
}
}
In case we want to load the font from an sdk we're using, of from a library we've written, we can include the font in the drawable raw section, and from the application using this sdk/lib we can reference the font like so:
(I've used the amaticobold font in this case just for example)
File sdCard = Environment.getExternalStorageDirectory();
File dir = new File (sdCard.getAbsolutePath() + "/fonts");
dir.mkdirs();
File file = new File(dir, "font.ttf");
InputStream is = getResources().openRawResource(getResources().getIdentifier("amaticbold","raw", getPackageName()));
try {
OutputStream out = new FileOutputStream(file);
byte[] buf = new byte[1024];
int len;
while((len=is.read(buf))>0){
out.write(buf,0,len);
}
out.close();
is.close();
} catch (Exception e) {
e.printStackTrace();
}
File sdcard = Environment.getExternalStorageDirectory();
File dirs = new File(sdcard.getAbsolutePath()+"/fonts");
if(dirs.exists()) {
File[] files = dirs.listFiles();
Log.d("s","files");
}
final Typeface typeface = Typeface.createFromFile(
new File(Environment.getExternalStorageDirectory()+"/fonts", "font.ttf"));
editText.setTypeface(typeface);
I have a arrays of apk files, what I need is to do write the apk files of ArrayList into cache storage and read it back again as same ArrayList. I know how to insert a single file and retrieve back again from the cache. But whereas ArrayList objects as concern I completely stuck up with the solutions and methodology. Please help me. I am using following code for read and write into cache memory. Any modification or slight changes in my code will be more helpful to me. Thanks in advance
Actual code for Read and write single File
//Write to cache dir
FileWriter writer = null;
try {
writer = new FileWriter(tmpFile);
writer.write(text.toString());
writer.close();
// path to file
// tmpFile.getPath()
} catch (IOException e) {
e.printStackTrace();
}
//Read to cache directory
String TMP_FILE_NAME = "base.apk";
File tmpFile;
File cacheDir = getBaseContext().getCacheDir();
tmpFile = new File(cacheDir.getPath() + "/" + TMP_FILE_NAME) ;
String line="";
StringBuilder text = new StringBuilder();
try {
FileReader fReader = new FileReader(tmpFile);
BufferedReader bReader = new BufferedReader(fReader);
while( (line=bReader.readLine()) != null ){
text.append(line+"\n");
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}catch(IOException e){
e.printStackTrace();
}
Modified code for my requirement to insert ArrayList<File>
String tempFile = null;
public void writeFile(ArrayList<File> files(){
for(File file: files) {
FileWriter writer = null;
try {
writer = new FileWriter(file);
tempFile = file.getName().toString();
writer.write(file.getName().toString());
writer.close();
// path to file
// tmpFile.getPath()
} catch (IOException e) {
e.printStackTrace();
}
}
}
This is where I stuck completely to read as ArrayList
What i tried is
String line="";
StringBuilder text = new StringBuilder();
try {
FileReader fReader = new FileReader(tempFile);
BufferedReader bReader = new BufferedReader(fReader);
while( (line=bReader.readLine()) != null ){
text.append(line+"\n");
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}catch(IOException e){
e.printStackTrace();
}
I found my own answer for my question after a longstruggle from the blog.
To Write a ArrayList<File>:
public static void createCachedFile (Context context, String key, ArrayList<File> fileName) throws IOException {
String tempFile = null;
for (File file : fileName) {
FileOutputStream fos = context.openFileOutput (key, Context.MODE_PRIVATE);
ObjectOutputStream oos = new ObjectOutputStream (fos);
oos.writeObject (fileName);
oos.close ();
fos.close ();
}
}
To Read a ArrayList<File>
public static Object readCachedFile (Context context, String key) throws IOException, ClassNotFoundException {
FileInputStream fis = context.openFileInput (key);
ObjectInputStream ois = new ObjectInputStream (fis);
Object object = ois.readObject ();
return object;
}
Final code in my Activity
createCachedFile (MainActivity.this,"apk",adapter.getAppList ());
ArrayList<File> apkCacheList = (ArrayList<File>)readCachedFile (MainActivity.this, "apk");
I want to return file object from assests folder. In Similar questions's response, it's returned InputStream class object, but I don't want to read content.
What I try to explain, there is an example.eg file in assests folder. I need to state this file as File file = new File(path).
Try this:
try {
BufferedReader r = new BufferedReader(new InputStreamReader(getAssets().open("example.csv")));
StringBuilder content = new StringBuilder();
String line;
while ((line = r.readLine()) != null) {
content(line);
}
} catch (IOException e) {
e.printStackTrace();
}
As far as I know, assets are not regular accessible files like others.
I used to copy them to internal storage and then use them.
Here is the basic idea of it:
final AssetManager assetManager = getAssets();
try {
for (final String asset : assetManager.list("")) {
final InputStream inputStream = assetManager.open(asset);
// ...
}
}
catch (IOException e) {
e.printStackTrace();
}
You can straight way create a file using InputStream.
AssetManager am = getAssets();
InputStream inputStream = am.open(file:///android_asset/myfoldername/myfilename);
File file = createFileFromInputStream(inputStream);
private File createFileFromInputStream(InputStream inputStream) {
try{
File f = new File(my_file_name);
OutputStream outputStream = new FileOutputStream(f);
byte buffer[] = new byte[1024];
int length = 0;
while((length=inputStream.read(buffer)) > 0) {
outputStream.write(buffer,0,length);
}
outputStream.close();
inputStream.close();
return f;
}catch (IOException e) {
//Logging exception
}
return null;
}