I am writing an android app where I am trying to read from a data base that I added in assets folder in main folder. But I am get an error file not found exception
public File database = new File("/assets/GeoIP2.mmdb");
PS : It's a database file not a text file.
This is the proper way to read files from assets folder
AssetManager am = context.getAssets();
InputStream is = am.open("GeoIP2.mmdb");
you can try this below code its working 100%
private String readFromFile(String name) {
String ret = "";
try {
InputStream inputStream = getAssets().open(name + ".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);
stringBuilder.append("\n");
}
inputStream.close();
ret = stringBuilder.toString();
}
} catch (FileNotFoundException e) {
Log.e(TAG, "File not found: " + e.toString());
} catch (IOException e) {
Log.e(TAG, "Can not read file: " + e.toString());
}
return ret;
}
just change the format of your file instead of .txt
InputStream is = getAssets().open("thirukkuralxml.xml");
try{
String verify, putData;
File file = new File("file.txt");
file.createNewFile();
FileWriter fw = new FileWriter(file);
BufferedWriter bw = new BufferedWriter(fw);
bw.write("Some text here for a reason");
bw.flush();
bw.close();
FileReader fr = new FileReader(file);
BufferedReader br = new BufferedReader(fr);
while( (verify=br.readLine()) != null ){ //***editted
//**deleted**verify = br.readLine();**
if(verify != null){ //***edited
putData = verify.replaceAll("here", "there");
bw.write(putData);
}
}
br.close();
}catch(IOException e){
e.printStackTrace();
}
Related
I am a newbie working with Android. A file is already created in the location data/data/myapp/files/hello.txt; the contents of this file is "hello". How do I read the file's content?
Take a look this how to use storages in android http://developer.android.com/guide/topics/data/data-storage.html#filesInternal
To read data from internal storage you need your app files folder and read content from here
String yourFilePath = context.getFilesDir() + "/" + "hello.txt";
File yourFile = new File( yourFilePath );
Also you can use this approach
FileInputStream fis = context.openFileInput("hello.txt");
InputStreamReader isr = new InputStreamReader(fis);
BufferedReader bufferedReader = new BufferedReader(isr);
StringBuilder sb = new StringBuilder();
String line;
while ((line = bufferedReader.readLine()) != null) {
sb.append(line);
}
Read a file as a string full version (handling exceptions, using UTF-8, handling new line):
// Calling:
/*
Context context = getApplicationContext();
String filename = "log.txt";
String str = read_file(context, filename);
*/
public String read_file(Context context, String filename) {
try {
FileInputStream fis = context.openFileInput(filename);
InputStreamReader isr = new InputStreamReader(fis, "UTF-8");
BufferedReader bufferedReader = new BufferedReader(isr);
StringBuilder sb = new StringBuilder();
String line;
while ((line = bufferedReader.readLine()) != null) {
sb.append(line).append("\n");
}
return sb.toString();
} catch (FileNotFoundException e) {
return "";
} catch (UnsupportedEncodingException e) {
return "";
} catch (IOException e) {
return "";
}
}
Note: you don't need to bother about file path only with file name.
Call To the following function with argument as you file path:
private String getFileContent(String targetFilePath) {
File file = new File(targetFilePath);
try {
fileInputStream = new FileInputStream(file);
} catch (FileNotFoundException e) {
Log.e("", "" + e.printStackTrace());
}
StringBuilder sb;
while (fileInputStream.available() > 0) {
if (null == sb) {
sb = new StringBuilder();
}
sb.append((char) fileInputStream.read());
}
String fileContent;
if (null != sb) {
fileContent = sb.toString();
// This is your file content in String.
}
try {
fileInputStream.close();
} catch (Exception e) {
Log.e("", "" + e.printStackTrace());
}
return fileContent;
}
String path = Environment.getExternalStorageDirectory().toString();
Log.d("Files", "Path: " + path);
File f = new File(path);
File file[] = f.listFiles();
Log.d("Files", "Size: " + file.length);
for (int i = 0; i < file.length; i++) {
//here populate your listview
Log.d("Files", "FileName:" + file[i].getName());
}
I prefer to use java.util.Scanner:
try {
Scanner scanner = new Scanner(context.openFileInput(filename)).useDelimiter("\\Z");
StringBuilder sb = new StringBuilder();
while (scanner.hasNext()) {
sb.append(scanner.next());
}
scanner.close();
String result = sb.toString();
} catch (IOException e) {}
For others looking for an answer to why a file is not readable especially on a sdcard, write the file like this first.. Notice the MODE_WORLD_READABLE
try {
FileOutputStream fos = Main.this.openFileOutput("exported_data.csv", MODE_WORLD_READABLE);
fos.write(csv.getBytes());
fos.close();
File file = Main.this.getFileStreamPath("exported_data.csv");
return file.getAbsolutePath();
} catch (Exception e) {
e.printStackTrace();
return null;
}
I'm trying to access the file path of my assets folder but for some reason, I can't access it and it creates an error(Unable to start activity ComponentInfo, Host name may not be null). What should be the correct syntax for this?
This is my code:
String xml = parser.getXmlFromUrl("file:///android_assets/music.xml");
and this is my file location:
Am I doing it properly? Or is my syntax incorrect?
try this, open an input stream on that file.
InputStreamReader is= new InputStreamReader(
context.getAssets().open("abc.xml"));
and then open and then
int length = is.available();
byte[] data = new byte[length];
is.read(data);
String xmlString = new String(data);
Hope It will help
Maybe
AssetManager assetManager = getAssets();
InputStream input = assetManager.open(fileName);
And after read file?
try using by filedescriptor as
AssetFileDescriptor descriptor = getAssets().openFd("myfile.txt");
FileReader reader = new FileReader(descriptor.getFileDescriptor());
Please use this code, its working code for text file as well as xml file.
public String readFromAssetsFolder(String fileName) {
String readValue = "";
InputStream fileInputStream = null;
InputStreamReader inputStreamReader = null;
BufferedReader input = null;
try {
fileInputStream = getResources().getAssets()
.open(fileName, Context.MODE_WORLD_READABLE);
inputStreamReader = new InputStreamReader(fileInputStream);
input = new BufferedReader(inputStreamReader);
String line = "";
while ((line = input.readLine()) != null) {
readValue = readValue+ line;
}
} catch (Exception e) {
e.getMessage();
} finally {
try {
if (inputStreamReader != null)
inputStreamReader.close();
if (fileInputStream != null)
fileInputStream.close();
if (input != null)
input.close();
} catch (Exception e2) {
e2.getMessage();
}
}
return readValue;
}
I am a newbie working with Android. A file is already created in the location data/data/myapp/files/hello.txt; the contents of this file is "hello". How do I read the file's content?
Take a look this how to use storages in android http://developer.android.com/guide/topics/data/data-storage.html#filesInternal
To read data from internal storage you need your app files folder and read content from here
String yourFilePath = context.getFilesDir() + "/" + "hello.txt";
File yourFile = new File( yourFilePath );
Also you can use this approach
FileInputStream fis = context.openFileInput("hello.txt");
InputStreamReader isr = new InputStreamReader(fis);
BufferedReader bufferedReader = new BufferedReader(isr);
StringBuilder sb = new StringBuilder();
String line;
while ((line = bufferedReader.readLine()) != null) {
sb.append(line);
}
Read a file as a string full version (handling exceptions, using UTF-8, handling new line):
// Calling:
/*
Context context = getApplicationContext();
String filename = "log.txt";
String str = read_file(context, filename);
*/
public String read_file(Context context, String filename) {
try {
FileInputStream fis = context.openFileInput(filename);
InputStreamReader isr = new InputStreamReader(fis, "UTF-8");
BufferedReader bufferedReader = new BufferedReader(isr);
StringBuilder sb = new StringBuilder();
String line;
while ((line = bufferedReader.readLine()) != null) {
sb.append(line).append("\n");
}
return sb.toString();
} catch (FileNotFoundException e) {
return "";
} catch (UnsupportedEncodingException e) {
return "";
} catch (IOException e) {
return "";
}
}
Note: you don't need to bother about file path only with file name.
Call To the following function with argument as you file path:
private String getFileContent(String targetFilePath) {
File file = new File(targetFilePath);
try {
fileInputStream = new FileInputStream(file);
} catch (FileNotFoundException e) {
Log.e("", "" + e.printStackTrace());
}
StringBuilder sb;
while (fileInputStream.available() > 0) {
if (null == sb) {
sb = new StringBuilder();
}
sb.append((char) fileInputStream.read());
}
String fileContent;
if (null != sb) {
fileContent = sb.toString();
// This is your file content in String.
}
try {
fileInputStream.close();
} catch (Exception e) {
Log.e("", "" + e.printStackTrace());
}
return fileContent;
}
String path = Environment.getExternalStorageDirectory().toString();
Log.d("Files", "Path: " + path);
File f = new File(path);
File file[] = f.listFiles();
Log.d("Files", "Size: " + file.length);
for (int i = 0; i < file.length; i++) {
//here populate your listview
Log.d("Files", "FileName:" + file[i].getName());
}
I prefer to use java.util.Scanner:
try {
Scanner scanner = new Scanner(context.openFileInput(filename)).useDelimiter("\\Z");
StringBuilder sb = new StringBuilder();
while (scanner.hasNext()) {
sb.append(scanner.next());
}
scanner.close();
String result = sb.toString();
} catch (IOException e) {}
For others looking for an answer to why a file is not readable especially on a sdcard, write the file like this first.. Notice the MODE_WORLD_READABLE
try {
FileOutputStream fos = Main.this.openFileOutput("exported_data.csv", MODE_WORLD_READABLE);
fos.write(csv.getBytes());
fos.close();
File file = Main.this.getFileStreamPath("exported_data.csv");
return file.getAbsolutePath();
} catch (Exception e) {
e.printStackTrace();
return null;
}
Hi everyone I am trying to read the date from a file in android. I am using Eclipse and the program is compiling and running, just it is not printing the context of the txt file. Here is my load method
private String load(String filename) {
try {
// Log.v("Home", " in the load method");
Log.d("Home", " in the load method");
final FileInputStream fis = openFileInput(filename);
// final InputStream fis = getResources().openRawResource(R.raw.pages);
final BufferedReader reader = new BufferedReader(new InputStreamReader(fis));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line);
}
reader.close();
fis.close();
return sb.toString();
} catch (Exception ex) {
return "No entry exists for this file";
}
}
and in the oncreate i just access it
String fileName = "pages.txt";
load(fileName);
pages.txt is in the res/raw directory. I tried to read the file with both
final FileInputStream fis = openFileInput(filename);
// final InputStream fis = getResources().openRawResource(R.raw.pages);
but It is not printing the context.
I added in the onCreate method
Log.d("File", load(fileName));
but is returning the catch statement No entry exists for this file.
Thanks
try to use like below,
System.out.println(load(raw.pages));
private String load(int id) {
try {
Resources res = getResources();
InputStream fis = res.openRawResource(id);
final BufferedReader reader = new BufferedReader(new InputStreamReader(fis));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line);
}
reader.close();
fis.close();
return sb.toString();
} catch (Exception ex) {
return "No entry exists for this file";
}
}
I need to load an xml file as String in android so I can load it to TBXML xml parser library and parse it. The implementation I have now to read the file as String takes around 2seconds even for a very small xml file of some KBs. Is there any known fast method that can read a file as string in Java/Android?
This is the code I have now:
public static String readFileAsString(String filePath) {
String result = "";
File file = new File(filePath);
if ( file.exists() ) {
//byte[] buffer = new byte[(int) new File(filePath).length()];
FileInputStream fis = null;
try {
//f = new BufferedInputStream(new FileInputStream(filePath));
//f.read(buffer);
fis = new FileInputStream(file);
char current;
while (fis.available() > 0) {
current = (char) fis.read();
result = result + String.valueOf(current);
}
} catch (Exception e) {
Log.d("TourGuide", e.toString());
} finally {
if (fis != null)
try {
fis.close();
} catch (IOException ignored) {
}
}
//result = new String(buffer);
}
return result;
}
The code finally used is the following from:
http://www.java2s.com/Code/Java/File-Input-Output/ConvertInputStreamtoString.htm
public static String convertStreamToString(InputStream is) throws Exception {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line).append("\n");
}
reader.close();
return sb.toString();
}
public static String getStringFromFile (String filePath) throws Exception {
File fl = new File(filePath);
FileInputStream fin = new FileInputStream(fl);
String ret = convertStreamToString(fin);
//Make sure you close all streams.
fin.close();
return ret;
}
You can use org.apache.commons.io.IOUtils.toString(InputStream is, Charset chs) to do that.
e.g.
IOUtils.toString(context.getResources().openRawResource(<your_resource_id>), StandardCharsets.UTF_8)
For adding the correct library:
Add the following to your app/build.gradle file:
dependencies {
compile 'org.apache.directory.studio:org.apache.commons.io:2.4'
}
https://stackoverflow.com/a/33820307/1815624
or for the Maven repo see -> this link
For direct jar download see-> https://commons.apache.org/proper/commons-io/download_io.cgi
Reworked the method set originating from -> the accepted answer
#JaredRummler An answer to your comment:
Read file As String
Won't this add an extra new line at the end of the string?
To prevent having a newline added at the end you can use a Boolean value set during the first loop as you will in the code example Boolean firstLine
public static String convertStreamToString(InputStream is) throws IOException {
// http://www.java2s.com/Code/Java/File-Input-Output/ConvertInputStreamtoString.htm
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
Boolean firstLine = true;
while ((line = reader.readLine()) != null) {
if(firstLine){
sb.append(line);
firstLine = false;
} else {
sb.append("\n").append(line);
}
}
reader.close();
return sb.toString();
}
public static String getStringFromFile (String filePath) throws IOException {
File fl = new File(filePath);
FileInputStream fin = new FileInputStream(fl);
String ret = convertStreamToString(fin);
//Make sure you close all streams.
fin.close();
return ret;
}
It's very easy if you use Kotlin:
val textFile = File(cacheDir, "/text_file.txt")
val allText = textFile.readText()
println(allText)
From readText() docs:
Gets the entire content of this file as a String using UTF-8 or
specified charset. This method is not recommended on huge files. It
has an internal limitation of 2 GB file size.
With files we know the size in advance, so just read it all at once!
String result;
File file = ...;
long length = file.length();
if (length < 1 || length > Integer.MAX_VALUE) {
result = "";
Log.w(TAG, "File is empty or huge: " + file);
} else {
try (FileReader in = new FileReader(file)) {
char[] content = new char[(int)length];
int numRead = in.read(content);
if (numRead != length) {
Log.e(TAG, "Incomplete read of " + file + ". Read chars " + numRead + " of " + length);
}
result = new String(content, 0, numRead);
}
catch (Exception ex) {
Log.e(TAG, "Failure reading " + this.file, ex);
result = "";
}
}
public static String readFileToString(String filePath) {
InputStream in = Test.class.getResourceAsStream(filePath);//filePath="/com/myproject/Sample.xml"
try {
return IOUtils.toString(in, StandardCharsets.UTF_8);
} catch (IOException e) {
logger.error("Failed to read the xml : ", e);
}
return null;
}
this is working for me
i use this path
String FILENAME_PATH = "/mnt/sdcard/Download/Version";
public static String getStringFromFile (String filePath) throws Exception {
File fl = new File(filePath);
FileInputStream fin = new FileInputStream(fl);
String ret = convertStreamToString(fin);
//Make sure you close all streams.
fin.close();
return ret;
}