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;
}
Related
Advance Thanks for your help!
I am searching for this solution for about two days but not solved yet. So, don't mark it as repetitive question.
Here, how I have tried-
Reading file path and setting to EditText: (it's working well)
I have used followings to read the file using that path-
buttond3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
File folders = new File(Environment.getExternalStorageDirectory() + "/" + "Information Security"+"/"+"Decrypted Files");
if (!folders.exists()) {
folders.mkdirs();
}
try {
String path= String.valueOf(editTextd2.getText());
String plain = getStringFromFile(path);
String decrypted = Encryption_Decryption2.decrypt(plain, "000102030405060708090A0B0C0D0E0F");
String file_name= String.valueOf(editTextd4.getText());
File f = new File(folders + "/" + file_name);
FileOutputStream fileOutput = new FileOutputStream(f);
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(fileOutput);
outputStreamWriter.write(decrypted);
outputStreamWriter.flush();
fileOutput.getFD().sync();
outputStreamWriter.close();
}
catch (Exception e) {
e.printStackTrace();
}
}
});
Here is the getStringFromFile() method-
public static String getStringFromFile (String filePath) throws Exception {
File fl = new File(filePath);
FileInputStream fin = new FileInputStream(fl);
String ret = convertStreamToString(fin);
fin.close();
return ret;
}
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();
}
Just problem in reading the file using the path. Please help!!!
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();
}
I have a .txt file which contains let's say
1;2;3;4;5
a;b;c;d;e
A;B;C;D;E
And I would like to remove the line which begins with "a"
I made a copy of the file and write there the lines unless the line equals the lineToRemove
So here what's I did but the file hasn't change
String path = "playlist.txt"
String lineToRemove = "a";
public boolean removeLineFromFile(String lineToRemove) {
try {
File inFile = new File(path);
//Creating a temp file
File tempFile = new File(inFile.getAbsolutePath()+".tmp");
FileInputStream fIn = openFileInput(path);
InputStreamReader isr = new InputStreamReader(fIn);
BufferedReader br = new BufferedReader(isr);
FileOutputStream fOut_temp = openFileOutput(path +".tmp", Context.MODE_APPEND);
OutputStreamWriter osw_temp = new OutputStreamWriter(fOut_temp);
osw_temp.write("");
String line = br.readLine();
//Read from the original file and write to the new
//unless content matches data to be removed.
while (line != null) {
String[] tokens = line.split(";");
if (! tokens[0].equals(lineToRemove)){
osw_temp.write(line);
osw_temp.flush();
}
line = br.readLine();
}
osw_temp.close();
br.close();
//Delete the original file
inFile.delete();
//Rename the new file to the filename the original file had.
tempFile.renameTo(inFile);
return true;
}catch (Exception ex) { return false;}
I think there is a problem with using File, is there another way of writing on android internal storage ?
Thanks in advance for your help
EDIT : because using File = new File + rename + deleted methods weren't working here is the solution that I find out. Maybe not the best but at least it works
try {
FileInputStream fIn = openFileInput(path);
InputStreamReader isr = new InputStreamReader(fIn);
BufferedReader br = new BufferedReader(isr);
//Create temp file
FileOutputStream fOut2 = openFileOutput("te.txt", Context.MODE_WORLD_WRITEABLE);
OutputStreamWriter osw2 = new OutputStreamWriter(fOut2);
osw2.write("");
// save and close
osw2.flush();
osw2.close();
// Adding things to temp file
FileOutputStream fOut_temp = openFileOutput("te.txt", Context.MODE_APPEND);
OutputStreamWriter osw_temp = new OutputStreamWriter(fOut_temp);
osw_temp.write("");
String line = br.readLine();
//Read from the original file and write to the new
//unless content matches data to be removed.
while (line != null) {
String[] tokens = line.split(";");
if (! tokens[0].equals(lineToRemove)){
osw_temp.write(line);
osw_temp.write("\r\n");
osw_temp.flush();
}
line = br.readLine();
}
osw_temp.close();
br.close();
//Delete the original file
FileOutputStream fOut = openFileOutput(path, Context.MODE_WORLD_WRITEABLE);
OutputStreamWriter osw = new OutputStreamWriter(fOut);
osw.write("");
// save and close
osw.flush();
osw.close();
//Copy temp file to original file
FileInputStream fIn3 = openFileInput("te.txt");
InputStreamReader isr3 = new InputStreamReader(fIn3);
BufferedReader br2 = new BufferedReader(isr3);
String line4 = br2.readLine() ;
FileOutputStream fOut_temp4 = openFileOutput(path, Context.MODE_APPEND);
OutputStreamWriter osw_temp4 = new OutputStreamWriter(fOut_temp4);
while (line4 != null) {
osw_temp4.write(line4);
osw_temp4.write("\r\n");
osw_temp4.flush();
Toast.makeText(getApplicationContext(),"ecrit", Toast.LENGTH_SHORT).show();
line4 = br2.readLine();
}
osw_temp4.close();
br2.close();
return true;
}catch (Exception ex) {
Toast.makeText(getApplicationContext(),ex.getMessage(), Toast.LENGTH_SHORT).show();
return false;}
}
Using this with Java I'm able to remove the line starts with a, just port in Android thats it.
public class LineRemover
{
static String path = "temp.txt";
static String lineToRemove = "a";
public static void main(String[] args)
{
try {
File inFile = new File(path);
FileInputStream fIn = new FileInputStream(path);
InputStreamReader isr = new InputStreamReader(fIn);
BufferedReader br = new BufferedReader(isr);
FileOutputStream fOut_temp = new FileOutputStream("te.txt");
OutputStreamWriter osw_temp = new OutputStreamWriter(fOut_temp);
osw_temp.write("");
String line = br.readLine();
//Read from the original file and write to the new
//unless content matches data to be removed.
while (line != null) {
String[] tokens = line.split(";");
if (! tokens[0].equals(lineToRemove)){
osw_temp.write(line);
osw_temp.flush();
}
line = br.readLine();
}
osw_temp.close();
br.close();
inFile.delete();
inFile = new File("te.txt");
//Rename the new file to the filename the original file had.
inFile.renameTo(new File("temp.txt"));
}catch (Exception ex)
{}
}
}
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'm porting the application from Symbian/iPhone to Android, part of which is saving some data into file. I used the FileOutputStream to save the file into private folder /data/data/package_name/files:
FileOutputStream fos = iContext.openFileOutput( IDS_LIST_FILE_NAME, Context.MODE_PRIVATE );
fos.write( data.getBytes() );
fos.close();
Now I am looking for a way how to load them. I am using the FileInputStream, but it allows me to read the file byte by byte, which is pretty inefficient:
int ch;
StringBuffer fileContent = new StringBuffer("");
FileInputStream fis = iContext.openFileInput( IDS_LIST_FILE_NAME );
while( (ch = fis.read()) != -1)
fileContent.append((char)ch);
String data = new String(fileContent);
So my question is how to read the file using better way?
Using FileInputStream.read(byte[]) you can read much more efficiently.
In general you don't want to be reading arbitrary-sized files into memory.
Most parsers will take an InputStream. Perhaps you could let us know how you're using the file and we could suggest a better fit.
Here is how you use the byte buffer version of read():
byte[] buffer = new byte[1024];
int length;
while ((length = fis.read(buffer)) != -1) {
fileContent.append(new String(buffer));
}
This isn't really Android-specific but more Java oriented.
If you prefer line-oriented reading instead, you could wrap the FileInputStream in an InputStreamReader which you can then pass to a BufferedReader. The BufferedReader instance has a readLine() method you can use to read line by line.
InputStreamReader in = new InputStreamReader(fis);
BufferedReader br = new BufferedReader(in);
String data = br.readLine()
Alternatively, if you use the Google Guava library you can use the convenience function in ByteStreams:
String data = new String(ByteStreams.toByteArray(fis));
//to write
String data = "Hello World";
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(openFileOutput(FILENAME,
Context.MODE_PRIVATE));
outputStreamWriter.write(data);
outputStreamWriter.close();
//to read
String ret = "";
try {
InputStream inputStream = openFileInput(FILENAME);
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(TAG, "File not found: " + e.toString());
} catch (IOException e) {
Log.e(TAG, "Can not read file: " + e.toString());
}
return ret;
}
context.getFilesDir() returns File object of the directory where context.openFileOutput() did the file writing.