Saving int values to SD and read them - android

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

Related

Can not resolve getAssets() method from inside a java file: Android

I have created a file
inside assests folder and now I want to read the file from a java class and pass it to another function in the same class but for some reason i am unable to use getAssest() method. Please help!
public void configuration()
{
String text = "";
try {
InputStream is = getAssets().open("config.txt");
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
text = new String(buffer);
} catch (IOException e) {
e.printStackTrace();
}
}
public IExtraFeeCalculator getExtraFeeCalculator()
{
if(efCalculator==null)
{
if(configuration(Context context) == "extrafeeCalculaotor")
{
String className = System.getProperty("extraFeeCalculator.class.name");
try {
efCalculator = (IExtraFeeCalculator)Class.forName(className).newInstance();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
return efCalculator;
}
You should try
getResources().getAssets().open("config.txt")
instead of
context.getAssets().open("config.txt");
Change your Method with Single Parameter Context ....
Pass Context from where you Call this Method..
public void configuration(Context context)
{
String text = "";
try {
InputStream is = context.getAssets().open("config.txt");
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
text = new String(buffer);
} catch (IOException e) {
e.printStackTrace();
}
}
Yes now as per i think you are not aware from java structure...
Suppose you have this YOUR_CLASS_NAME.java
public void YOUR_CLASS_NAME{
Context context;
YOUR_CLASS_NAME(Context context){
this.context=context;
}
public void configuration(Context context)
{
String text = "";
try {
InputStream is = getAssets().open("config.txt");
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
text = new String(buffer);
} catch (IOException e) {
e.printStackTrace();
}
}
public IExtraFeeCalculator getExtraFeeCalculator()
{
if(efCalculator==null)
{
if(configuration(context) == "extrafeeCalculaotor")
{
String className = System.getProperty("extraFeeCalculator.class.name");
try {
efCalculator = (IExtraFeeCalculator)Class.forName(className).newInstance();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
return efCalculator;
}
}
Use this Code
BufferedReader reader = null;
try {
StringBuilder returnString = new StringBuilder();
reader = new BufferedReader(
new InputStreamReader(getAssets().open("filename.txt")));
String mLine;
while ((mLine = reader.readLine()) != null) {
//process line
returnString.append(mLine );
}
} catch (IOException e) {
//log the exception
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
//log the exception
}
}
}

ANDROID: How to save JSON data in a file and retrieve it?

I'm new to android so please help me out. I am trying to save my ToDoList in a file so that the next time I open it, all the items are reloaded
This is the code I have so far,
MainActivity.java
#Override
protected void onCreate(Bundle savedInstanceState) {
gson = new Gson();
try {
BufferedReader br = new BufferedReader(new FileReader("storage.json"));
Entry e = gson.fromJson(br, Entry.class);
Log.d("reading", e.toString());
} catch (FileNotFoundException e) {
e.printStackTrace();
}}
#Override
protected void onStop() {
super.onStop();
json = gson.toJson(mEntries);
Log.d("jsondata", json);
try {
file1 = new FileWriter("storage.json");
file1.write(json);
file1.flush();
file1.close();
} catch (IOException e) {
e.printStackTrace();
}
Entry.java
public class Entry {
String S;
boolean b;
public Entry(String S, boolean b) {
this.S = S;
this.b = b;
}
public String getS() {
return S;
}
public void setS(String S) {
this.S = S;
}
public void setB(boolean b) {
this.b = b;
}
public boolean isB() {
return b;
}
}
How do I proceed from here? In onCreate() I would like to check if the file exists and if yes, import data from file and display on screen.
Every android app has its own internal storage only that app can access, you can read from there or write to it.
In you case, you first want to check if you such file exist before creating one.
private String read(Context context, String fileName) {
try {
FileInputStream fis = context.openFileInput(fileName);
InputStreamReader isr = new InputStreamReader(fis);
BufferedReader bufferedReader = new BufferedReader(isr);
StringBuilder sb = new StringBuilder();
String line;
while ((line = bufferedReader.readLine()) != null) {
sb.append(line);
}
return sb.toString();
} catch (FileNotFoundException fileNotFound) {
return null;
} catch (IOException ioException) {
return null;
}
}
private boolean create(Context context, String fileName, String jsonString){
String FILENAME = "storage.json";
try {
FileOutputStream fos = context.openFileOutput(fileName,Context.MODE_PRIVATE);
if (jsonString != null) {
fos.write(jsonString.getBytes());
}
fos.close();
return true;
} catch (FileNotFoundException fileNotFound) {
return false;
} catch (IOException ioException) {
return false;
}
}
public boolean isFilePresent(Context context, String fileName) {
String path = context.getFilesDir().getAbsolutePath() + "/" + fileName;
File file = new File(path);
return file.exists();
}
onCreate of the Activity, you can use do the following
boolean isFilePresent = isFilePresent(getActivity(), "storage.json");
if(isFilePresent) {
String jsonString = read(getActivity(), "storage.json");
//do the json parsing here and do the rest of functionality of app
} else {
boolean isFileCreated = create(getActivity, "storage.json", "{}");
if(isFileCreated) {
//proceed with storing the first todo or show ui
} else {
//show error or try again.
}
}
reference https://developer.android.com/guide/topics/data/data-storage.html#filesInternal

Wordnet with Android [duplicate]

public class Utils {
public static List<Message> getMessages() {
//File file = new File("file:///android_asset/helloworld.txt");
AssetManager assetManager = getAssets();
InputStream ims = assetManager.open("helloworld.txt");
}
}
I am using this code trying to read a file from assets. I tried two ways to do this. First, when use File I received FileNotFoundException, when using AssetManager getAssets() method isn't recognized.
Is there any solution here?
Here is what I do in an activity for buffered reading extend/modify to match your needs
BufferedReader reader = null;
try {
reader = new BufferedReader(
new InputStreamReader(getAssets().open("filename.txt")));
// do reading, usually loop until end of file reading
String mLine;
while ((mLine = reader.readLine()) != null) {
//process line
...
}
} catch (IOException e) {
//log the exception
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
//log the exception
}
}
}
EDIT : My answer is perhaps useless if your question is on how to do it outside of an activity. If your question is simply how to read a file from asset then the answer is above.
UPDATE :
To open a file specifying the type simply add the type in the InputStreamReader call as follow.
BufferedReader reader = null;
try {
reader = new BufferedReader(
new InputStreamReader(getAssets().open("filename.txt"), "UTF-8"));
// do reading, usually loop until end of file reading
String mLine;
while ((mLine = reader.readLine()) != null) {
//process line
...
}
} catch (IOException e) {
//log the exception
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
//log the exception
}
}
}
EDIT
As #Stan says in the comment, the code I am giving is not summing up lines. mLine is replaced every pass. That's why I wrote //process line. I assume the file contains some sort of data (i.e a contact list) and each line should be processed separately.
In case you simply want to load the file without any kind of processing you will have to sum up mLine at each pass using StringBuilder() and appending each pass.
ANOTHER EDIT
According to the comment of #Vincent I added the finally block.
Also note that in Java 7 and upper you can use try-with-resources to use the AutoCloseable and Closeable features of recent Java.
CONTEXT
In a comment #LunarWatcher points out that getAssets() is a class in context. So, if you call it outside of an activity you need to refer to it and pass the context instance to the activity.
ContextInstance.getAssets();
This is explained in the answer of #Maneesh. So if this is useful to you upvote his answer because that's him who pointed that out.
getAssets()
is only works in Activity in other any class you have to use Context for it.
Make a constructor for Utils class pass reference of activity (ugly way) or context of application as a parameter to it. Using that use getAsset() in your Utils class.
Better late than never.
I had difficulties reading files line by line in some circumstances.
The method below is the best I found, so far, and I recommend it.
Usage: String yourData = LoadData("YourDataFile.txt");
Where YourDataFile.txt is assumed to reside in assets/
public String LoadData(String inFile) {
String tContents = "";
try {
InputStream stream = getAssets().open(inFile);
int size = stream.available();
byte[] buffer = new byte[size];
stream.read(buffer);
stream.close();
tContents = new String(buffer);
} catch (IOException e) {
// Handle exceptions here
}
return tContents;
}
public String ReadFromfile(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();
}
one line solution for kotlin:
fun readFileText(fileName: String): String {
return assets.open(fileName).bufferedReader().use { it.readText() }
}
Also you can use it as extension function everyWhere
fun Context.readTextFromAsset(fileName : String) : String{
return assets.open(fileName).bufferedReader().use {
it.readText()}
}
Simply call in any context Class
context.readTextFromAsset("my file name")
AssetManager assetManager = getAssets();
InputStream inputStream = null;
try {
inputStream = assetManager.open("helloworld.txt");
}
catch (IOException e){
Log.e("message: ",e.getMessage());
}
getAssets() method will work when you are calling inside the Activity class.
If you calling this method in non-Activity class then you need to call this method from Context which is passed from Activity class. So below is the line by you can access the method.
ContextInstance.getAssets();
ContextInstance may be passed as this of Activity class.
Reading and writing files have always been verbose and error-prone. Avoid these answers and just use Okio instead:
public void readLines(File file) throws IOException {
try (BufferedSource source = Okio.buffer(Okio.source(file))) {
for (String line; (line = source.readUtf8Line()) != null; ) {
if (line.contains("square")) {
System.out.println(line);
}
}
}
}
Here is a method to read a file in assets:
/**
* Reads the text of an asset. Should not be run on the UI thread.
*
* #param mgr
* The {#link AssetManager} obtained via {#link Context#getAssets()}
* #param path
* The path to the asset.
* #return The plain text of the asset
*/
public static String readAsset(AssetManager mgr, String path) {
String contents = "";
InputStream is = null;
BufferedReader reader = null;
try {
is = mgr.open(path);
reader = new BufferedReader(new InputStreamReader(is));
contents = reader.readLine();
String line = null;
while ((line = reader.readLine()) != null) {
contents += '\n' + line;
}
} catch (final Exception e) {
e.printStackTrace();
} finally {
if (is != null) {
try {
is.close();
} catch (IOException ignored) {
}
}
if (reader != null) {
try {
reader.close();
} catch (IOException ignored) {
}
}
}
return contents;
}
You can load the content from the file. Consider the file is present in asset folder.
public static InputStream loadInputStreamFromAssetFile(Context context, String fileName){
AssetManager am = context.getAssets();
try {
InputStream is = am.open(fileName);
return is;
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
public static String loadContentFromFile(Context context, String path){
String content = null;
try {
InputStream is = loadInputStreamFromAssetFile(context, path);
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
content = new String(buffer, "UTF-8");
} catch (IOException ex) {
ex.printStackTrace();
return null;
}
return content;
}
Now you can get the content by calling the function as follow
String json= FileUtil.loadContentFromFile(context, "data.json");
Considering the data.json is stored at Application\app\src\main\assets\data.json
In MainActivity.java
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView tvView = (TextView) findViewById(R.id.tvView);
AssetsReader assetsReader = new AssetsReader(this);
if(assetsReader.getTxtFile(your_file_title)) != null)
{
tvView.setText(assetsReader.getTxtFile(your_file_title)));
}
}
Also, you can create separate class that does all the work
public class AssetsReader implements Readable{
private static final String TAG = "AssetsReader";
private AssetManager mAssetManager;
private Activity mActivity;
public AssetsReader(Activity activity) {
this.mActivity = activity;
mAssetManager = mActivity.getAssets();
}
#Override
public String getTxtFile(String fileName)
{
BufferedReader reader = null;
InputStream inputStream = null;
StringBuilder builder = new StringBuilder();
try{
inputStream = mAssetManager.open(fileName);
reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while((line = reader.readLine()) != null)
{
Log.i(TAG, line);
builder.append(line);
builder.append("\n");
}
} catch (IOException ioe){
ioe.printStackTrace();
} finally {
if(inputStream != null)
{
try {
inputStream.close();
} catch (IOException ioe){
ioe.printStackTrace();
}
}
if(reader != null)
{
try {
reader.close();
} catch (IOException ioe)
{
ioe.printStackTrace();
}
}
}
Log.i(TAG, "builder.toString(): " + builder.toString());
return builder.toString();
}
}
In my opinion it's better to create an interface, but it's not neccessary
public interface Readable {
/**
* Reads txt file from assets
* #param fileName
* #return string
*/
String getTxtFile(String fileName);
}
Here is a way to get an InputStream for a file in the assets folder without a Context, Activity, Fragment or Application. How you get the data from that InputStream is up to you. There are plenty of suggestions for that in other answers here.
Kotlin
val inputStream = ClassLoader::class.java.classLoader?.getResourceAsStream("assets/your_file.ext")
Java
InputStream inputStream = ClassLoader.class.getClassLoader().getResourceAsStream("assets/your_file.ext");
All bets are off if a custom ClassLoader is in play.
ExceptionProof
It maybe too late but for the sake of others who look for the peachy answers.
loadAssetFile() method returns the plain text of the asset, or defaultValue argument if anything goes wrong.
public static String loadAssetFile(Context context, String fileName, String defaultValue) {
String result=defaultValue;
InputStreamReader inputStream=null;
BufferedReader bufferedReader=null;
try {
inputStream = new InputStreamReader(context.getAssets().open(fileName));
bufferedReader = new BufferedReader(inputStream);
StringBuilder out= new StringBuilder();
String line = bufferedReader.readLine();
while (line != null) {
out.append(line);
line = bufferedReader.readLine();
}
result=out.toString();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
Objects.requireNonNull(inputStream).close();
} catch (Exception e) {
e.printStackTrace();
}
try {
Objects.requireNonNull(bufferedReader).close();
} catch (Exception e) {
e.printStackTrace();
}
}
return result;
}
If you use other any class other than Activity, you might want to do like,
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader( YourApplication.getInstance().getAssets().open("text.txt"), "UTF-8"));
Using Kotlin, you can do the following to read a file from assets in Android:
try {
val inputStream:InputStream = assets.open("helloworld.txt")
val inputString = inputStream.bufferedReader().use{it.readText()}
Log.d(TAG,inputString)
} catch (e:Exception){
Log.d(TAG, e.toString())
}
cityfile.txt
public void getCityStateFromLocal() {
AssetManager am = getAssets();
InputStream inputStream = null;
try {
inputStream = am.open("city_state.txt");
} catch (IOException e) {
e.printStackTrace();
}
ObjectMapper mapper = new ObjectMapper();
Map<String, String[]> map = new HashMap<String, String[]>();
try {
map = mapper.readValue(getStringFromInputStream(inputStream), new TypeReference<Map<String, String[]>>() {
});
} catch (IOException e) {
e.printStackTrace();
}
ConstantValues.arrayListStateName.clear();
ConstantValues.arrayListCityByState.clear();
if (map.size() > 0)
{
for (Map.Entry<String, String[]> e : map.entrySet()) {
CityByState cityByState = new CityByState();
String key = e.getKey();
String[] value = e.getValue();
ArrayList<String> s = new ArrayList<String>(Arrays.asList(value));
ConstantValues.arrayListStateName.add(key);
s.add(0,"Select City");
cityByState.addValue(s);
ConstantValues.arrayListCityByState.add(cityByState);
}
}
ConstantValues.arrayListStateName.add(0,"Select States");
}
// Convert InputStream to String
public String getStringFromInputStream(InputStream is) {
BufferedReader br = null;
StringBuilder sb = new StringBuilder();
String line;
try {
br = new BufferedReader(new InputStreamReader(is));
while ((line = br.readLine()) != null) {
sb.append(line);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return sb + "";
}
The Scanner class may simplify this.
StringBuilder sb=new StringBuilder();
Scanner scanner=null;
try {
scanner=new Scanner(getAssets().open("text.txt"));
while(scanner.hasNextLine()){
sb.append(scanner.nextLine());
sb.append('\n');
}
} catch (IOException e) {
e.printStackTrace();
}finally {
if(scanner!=null){try{scanner.close();}catch (Exception e){}}
}
mTextView.setText(sb.toString());
#HpTerm answer Kotlin version:
private fun getDataFromAssets(activity: Activity): String {
var bufferedReader: BufferedReader? = null
var data = ""
try {
bufferedReader = BufferedReader(
InputStreamReader(
activity?.assets?.open("Your_FILE.html"),
"UTF-8"
)
) //use assets? directly if inside the activity
var mLine:String? = bufferedReader.readLine()
while (mLine != null) {
data+= mLine
mLine=bufferedReader.readLine()
}
} catch (e: Exception) {
e.printStackTrace()
} finally {
try {
bufferedReader?.close()
} catch (e: Exception) {
e.printStackTrace()
}
}
return data
}

How to find index of the line?

i am using following code to read data from file but i am unable to find index of the line?
public static ArrayList<String> searchInFile(String word) {
ArrayList<String> result = new ArrayList<String>();
FileReader fileReader = null;
try {
fileReader = new FileReader(new File("input.txt"));
} catch (FileNotFoundException e1) {
System.err.println("File input.txt not found!");
e1.printStackTrace();
}
BufferedReader br = new BufferedReader(file);
String line;
try {
while ((line = br.readLine()) != null) {
if (line.contains(word)) {
result.Add(line);
}
}
} catch (IOException e) {
System.err.println("Error when processing the file!");
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
System.err.println("Unexpected error");
e.printStackTrace();
}
}
}
return result;
}
so how can i find index of the line??
You would need to create a counter integer variable that can keep track of the line index for you.
int ctr =0;
while ((line = br.readLine()) != null) {
if (line.contains(word)) {
result.Add(line);
}
ctr++;
}
Hope it helps!

read file from assets

public class Utils {
public static List<Message> getMessages() {
//File file = new File("file:///android_asset/helloworld.txt");
AssetManager assetManager = getAssets();
InputStream ims = assetManager.open("helloworld.txt");
}
}
I am using this code trying to read a file from assets. I tried two ways to do this. First, when use File I received FileNotFoundException, when using AssetManager getAssets() method isn't recognized.
Is there any solution here?
Here is what I do in an activity for buffered reading extend/modify to match your needs
BufferedReader reader = null;
try {
reader = new BufferedReader(
new InputStreamReader(getAssets().open("filename.txt")));
// do reading, usually loop until end of file reading
String mLine;
while ((mLine = reader.readLine()) != null) {
//process line
...
}
} catch (IOException e) {
//log the exception
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
//log the exception
}
}
}
EDIT : My answer is perhaps useless if your question is on how to do it outside of an activity. If your question is simply how to read a file from asset then the answer is above.
UPDATE :
To open a file specifying the type simply add the type in the InputStreamReader call as follow.
BufferedReader reader = null;
try {
reader = new BufferedReader(
new InputStreamReader(getAssets().open("filename.txt"), "UTF-8"));
// do reading, usually loop until end of file reading
String mLine;
while ((mLine = reader.readLine()) != null) {
//process line
...
}
} catch (IOException e) {
//log the exception
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
//log the exception
}
}
}
EDIT
As #Stan says in the comment, the code I am giving is not summing up lines. mLine is replaced every pass. That's why I wrote //process line. I assume the file contains some sort of data (i.e a contact list) and each line should be processed separately.
In case you simply want to load the file without any kind of processing you will have to sum up mLine at each pass using StringBuilder() and appending each pass.
ANOTHER EDIT
According to the comment of #Vincent I added the finally block.
Also note that in Java 7 and upper you can use try-with-resources to use the AutoCloseable and Closeable features of recent Java.
CONTEXT
In a comment #LunarWatcher points out that getAssets() is a class in context. So, if you call it outside of an activity you need to refer to it and pass the context instance to the activity.
ContextInstance.getAssets();
This is explained in the answer of #Maneesh. So if this is useful to you upvote his answer because that's him who pointed that out.
getAssets()
is only works in Activity in other any class you have to use Context for it.
Make a constructor for Utils class pass reference of activity (ugly way) or context of application as a parameter to it. Using that use getAsset() in your Utils class.
Better late than never.
I had difficulties reading files line by line in some circumstances.
The method below is the best I found, so far, and I recommend it.
Usage: String yourData = LoadData("YourDataFile.txt");
Where YourDataFile.txt is assumed to reside in assets/
public String LoadData(String inFile) {
String tContents = "";
try {
InputStream stream = getAssets().open(inFile);
int size = stream.available();
byte[] buffer = new byte[size];
stream.read(buffer);
stream.close();
tContents = new String(buffer);
} catch (IOException e) {
// Handle exceptions here
}
return tContents;
}
public String ReadFromfile(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();
}
one line solution for kotlin:
fun readFileText(fileName: String): String {
return assets.open(fileName).bufferedReader().use { it.readText() }
}
Also you can use it as extension function everyWhere
fun Context.readTextFromAsset(fileName : String) : String{
return assets.open(fileName).bufferedReader().use {
it.readText()}
}
Simply call in any context Class
context.readTextFromAsset("my file name")
AssetManager assetManager = getAssets();
InputStream inputStream = null;
try {
inputStream = assetManager.open("helloworld.txt");
}
catch (IOException e){
Log.e("message: ",e.getMessage());
}
getAssets() method will work when you are calling inside the Activity class.
If you calling this method in non-Activity class then you need to call this method from Context which is passed from Activity class. So below is the line by you can access the method.
ContextInstance.getAssets();
ContextInstance may be passed as this of Activity class.
Reading and writing files have always been verbose and error-prone. Avoid these answers and just use Okio instead:
public void readLines(File file) throws IOException {
try (BufferedSource source = Okio.buffer(Okio.source(file))) {
for (String line; (line = source.readUtf8Line()) != null; ) {
if (line.contains("square")) {
System.out.println(line);
}
}
}
}
Here is a method to read a file in assets:
/**
* Reads the text of an asset. Should not be run on the UI thread.
*
* #param mgr
* The {#link AssetManager} obtained via {#link Context#getAssets()}
* #param path
* The path to the asset.
* #return The plain text of the asset
*/
public static String readAsset(AssetManager mgr, String path) {
String contents = "";
InputStream is = null;
BufferedReader reader = null;
try {
is = mgr.open(path);
reader = new BufferedReader(new InputStreamReader(is));
contents = reader.readLine();
String line = null;
while ((line = reader.readLine()) != null) {
contents += '\n' + line;
}
} catch (final Exception e) {
e.printStackTrace();
} finally {
if (is != null) {
try {
is.close();
} catch (IOException ignored) {
}
}
if (reader != null) {
try {
reader.close();
} catch (IOException ignored) {
}
}
}
return contents;
}
You can load the content from the file. Consider the file is present in asset folder.
public static InputStream loadInputStreamFromAssetFile(Context context, String fileName){
AssetManager am = context.getAssets();
try {
InputStream is = am.open(fileName);
return is;
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
public static String loadContentFromFile(Context context, String path){
String content = null;
try {
InputStream is = loadInputStreamFromAssetFile(context, path);
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
content = new String(buffer, "UTF-8");
} catch (IOException ex) {
ex.printStackTrace();
return null;
}
return content;
}
Now you can get the content by calling the function as follow
String json= FileUtil.loadContentFromFile(context, "data.json");
Considering the data.json is stored at Application\app\src\main\assets\data.json
In MainActivity.java
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView tvView = (TextView) findViewById(R.id.tvView);
AssetsReader assetsReader = new AssetsReader(this);
if(assetsReader.getTxtFile(your_file_title)) != null)
{
tvView.setText(assetsReader.getTxtFile(your_file_title)));
}
}
Also, you can create separate class that does all the work
public class AssetsReader implements Readable{
private static final String TAG = "AssetsReader";
private AssetManager mAssetManager;
private Activity mActivity;
public AssetsReader(Activity activity) {
this.mActivity = activity;
mAssetManager = mActivity.getAssets();
}
#Override
public String getTxtFile(String fileName)
{
BufferedReader reader = null;
InputStream inputStream = null;
StringBuilder builder = new StringBuilder();
try{
inputStream = mAssetManager.open(fileName);
reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while((line = reader.readLine()) != null)
{
Log.i(TAG, line);
builder.append(line);
builder.append("\n");
}
} catch (IOException ioe){
ioe.printStackTrace();
} finally {
if(inputStream != null)
{
try {
inputStream.close();
} catch (IOException ioe){
ioe.printStackTrace();
}
}
if(reader != null)
{
try {
reader.close();
} catch (IOException ioe)
{
ioe.printStackTrace();
}
}
}
Log.i(TAG, "builder.toString(): " + builder.toString());
return builder.toString();
}
}
In my opinion it's better to create an interface, but it's not neccessary
public interface Readable {
/**
* Reads txt file from assets
* #param fileName
* #return string
*/
String getTxtFile(String fileName);
}
Here is a way to get an InputStream for a file in the assets folder without a Context, Activity, Fragment or Application. How you get the data from that InputStream is up to you. There are plenty of suggestions for that in other answers here.
Kotlin
val inputStream = ClassLoader::class.java.classLoader?.getResourceAsStream("assets/your_file.ext")
Java
InputStream inputStream = ClassLoader.class.getClassLoader().getResourceAsStream("assets/your_file.ext");
All bets are off if a custom ClassLoader is in play.
ExceptionProof
It maybe too late but for the sake of others who look for the peachy answers.
loadAssetFile() method returns the plain text of the asset, or defaultValue argument if anything goes wrong.
public static String loadAssetFile(Context context, String fileName, String defaultValue) {
String result=defaultValue;
InputStreamReader inputStream=null;
BufferedReader bufferedReader=null;
try {
inputStream = new InputStreamReader(context.getAssets().open(fileName));
bufferedReader = new BufferedReader(inputStream);
StringBuilder out= new StringBuilder();
String line = bufferedReader.readLine();
while (line != null) {
out.append(line);
line = bufferedReader.readLine();
}
result=out.toString();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
Objects.requireNonNull(inputStream).close();
} catch (Exception e) {
e.printStackTrace();
}
try {
Objects.requireNonNull(bufferedReader).close();
} catch (Exception e) {
e.printStackTrace();
}
}
return result;
}
If you use other any class other than Activity, you might want to do like,
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader( YourApplication.getInstance().getAssets().open("text.txt"), "UTF-8"));
Using Kotlin, you can do the following to read a file from assets in Android:
try {
val inputStream:InputStream = assets.open("helloworld.txt")
val inputString = inputStream.bufferedReader().use{it.readText()}
Log.d(TAG,inputString)
} catch (e:Exception){
Log.d(TAG, e.toString())
}
cityfile.txt
public void getCityStateFromLocal() {
AssetManager am = getAssets();
InputStream inputStream = null;
try {
inputStream = am.open("city_state.txt");
} catch (IOException e) {
e.printStackTrace();
}
ObjectMapper mapper = new ObjectMapper();
Map<String, String[]> map = new HashMap<String, String[]>();
try {
map = mapper.readValue(getStringFromInputStream(inputStream), new TypeReference<Map<String, String[]>>() {
});
} catch (IOException e) {
e.printStackTrace();
}
ConstantValues.arrayListStateName.clear();
ConstantValues.arrayListCityByState.clear();
if (map.size() > 0)
{
for (Map.Entry<String, String[]> e : map.entrySet()) {
CityByState cityByState = new CityByState();
String key = e.getKey();
String[] value = e.getValue();
ArrayList<String> s = new ArrayList<String>(Arrays.asList(value));
ConstantValues.arrayListStateName.add(key);
s.add(0,"Select City");
cityByState.addValue(s);
ConstantValues.arrayListCityByState.add(cityByState);
}
}
ConstantValues.arrayListStateName.add(0,"Select States");
}
// Convert InputStream to String
public String getStringFromInputStream(InputStream is) {
BufferedReader br = null;
StringBuilder sb = new StringBuilder();
String line;
try {
br = new BufferedReader(new InputStreamReader(is));
while ((line = br.readLine()) != null) {
sb.append(line);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return sb + "";
}
The Scanner class may simplify this.
StringBuilder sb=new StringBuilder();
Scanner scanner=null;
try {
scanner=new Scanner(getAssets().open("text.txt"));
while(scanner.hasNextLine()){
sb.append(scanner.nextLine());
sb.append('\n');
}
} catch (IOException e) {
e.printStackTrace();
}finally {
if(scanner!=null){try{scanner.close();}catch (Exception e){}}
}
mTextView.setText(sb.toString());
#HpTerm answer Kotlin version:
private fun getDataFromAssets(activity: Activity): String {
var bufferedReader: BufferedReader? = null
var data = ""
try {
bufferedReader = BufferedReader(
InputStreamReader(
activity?.assets?.open("Your_FILE.html"),
"UTF-8"
)
) //use assets? directly if inside the activity
var mLine:String? = bufferedReader.readLine()
while (mLine != null) {
data+= mLine
mLine=bufferedReader.readLine()
}
} catch (e: Exception) {
e.printStackTrace()
} finally {
try {
bufferedReader?.close()
} catch (e: Exception) {
e.printStackTrace()
}
}
return data
}

Categories

Resources