see if file exist and create file in android - android

Hi i'm trying to create a file if the file not already exists. Then I want to write 11 zeros in 11 rows if the file not already existed and then read it to an 2d array. But the app crashes and i got the message "java.io.FileNotFoundException: /FILENAME: open failed: ENOENT (No such file or directory)" in logcat. I would really appreciate if someone could help me.
Here is my code:
public void empt(String fileName) {
File file = getBaseContext().getFileStreamPath(fileName);
if(file.exists()){
return 1;
}
else return 2;
}
public int[][] readFile2(String fileName) {
empt(fileName);
if(empty == 1){
FileOutputStream outputStream;
String row = "0 0 0 0 0 0 0 0 0 0 0";
String newline = "\n";
try {
outputStream = openFileOutput(fileName, Context.MODE_PRIVATE);
for(int i = 0; i <11; i++)
{
if(i == 10){
outputStream.write(row.getBytes());
}
else {
outputStream.write(row.getBytes());
outputStream.write(line.getBytes());
}
}
outputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
}
String line = "";
int[][] data = new int [11][11];
try {
BufferedReader br = new BufferedReader(new FileReader(fileName));
int i = 0;
while((line = br.readLine()) != null) { // line becomes the whole line ( 11 numbers on a row)
String[] theline = line.split(" "); // theline becomes an array with 11 numbers
for(int k = 0; k<11; k++)
{
data[i][k] = (Integer.parseInt(theline[k]));
}
i++;
}
br.close();
}
catch(FileNotFoundException fN) {
fN.printStackTrace();
}
catch(IOException e) {
System.out.println(e);
}
return data;
}

to read from the internal storage you have to use openFileInput.
Change
BufferedReader br = new BufferedReader(new FileReader(fileName));
with
FileInputStream fstream = openFileInput(fileName);
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));

Related

Extracting a storage_file's path then set it to a EditText and finally read that file using that path placed in EditText

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!!!

Reading a file in android

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

Opening a file and returning a Bitmap [duplicate]

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

How do I read the file content from the Internal storage - Android App

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

Read file As String

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

Categories

Resources