example of read file from assets - android

I'm working on example that make app read file from assets but it's not work, the text inside the (file.txt) doesn't appear.
code :
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_read_file);
b_read= (Button)findViewById(R.id.b_read);
tv_text= (TextView) findViewById(R.id.tv_text);
b_read.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String text="";
try{
InputStream is = getAssets().open("file.txt");
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
text = new String(buffer);
}catch (IOException ex) {
ex.printStackTrace();
}
tv_text.setText(text);
}
});
Can you help?

use this
StringBuilder DataString = new StringBuilder();
InputStream fIn = null;
InputStreamReader isr = null;
BufferedReader input = null;
try {
fIn = getAssets()
.open("file.txt", Context.MODE_WORLD_READABLE);
isr = new InputStreamReader(fIn);
input = new BufferedReader(isr);
String line = "";
while ((line = input.readLine()) != null) {
DataString.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();
}
}
tv_text.setText(DataString.toString());
even though your method is correct it would return 'android.content.res.AssetManager$AssetInputStream#[code]' some times
look at this answer and comments

In this example i'm reading tests.json from /assets folder:
public class Constants {
public static final String BASE_DIR = "arqospocket";
public static final String CONFIG_DIR = "cfg";
public static final String TESTS_DIR = "tests";
public static final String TESTS_FILE = "tests.json";
}
private String getJsonTestList() {
String path = Environment.getExternalStorageDirectory().getAbsolutePath()
+ File.separator
+ BASE_DIR
+ File.separator
+ TESTS_DIR;
final File file = new File(path, TESTS_FILE);
if(file.exists()){
Log.d(TAG, "getJsonTestList :: Reading tests from external file: " + file.getAbsolutePath());
StringBuilder text = new StringBuilder();
try {
BufferedReader br = new BufferedReader(new FileReader(file));
String line = null;
while ((line = br.readLine()) != null) {
text.append(line);
}
br.close();
return text.toString();
} catch (IOException e) {
Log.d(TAG, "getJsonTestList :: Exception reading from external file: " + e.getMessage());
}
}
//TODO remove this
Log.d(TAG, "getJsonTestList :: Reading tests from asset manager" );
AssetManager assetManager = getAssets();
ByteArrayOutputStream outputStream = null;
InputStream inputStream = null;
try {
inputStream = assetManager.open("tests.json");
outputStream = new ByteArrayOutputStream();
byte buf[] = new byte[8192];
int len;
try {
while ((len = inputStream.read(buf)) != -1) {
outputStream.write(buf, 0, len);
}
outputStream.close();
inputStream.close();
} catch (IOException e) {
}
} catch (IOException e) {
}
return outputStream.toString();
}

Related

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

FILE TRANSFER in android

this is regarding android instant messenger. im trying to send a file, and this is how i send it :
#Override
public boolean sendFile(String path,String ip, int port) {
// TODO Auto-generated method stub
try {
String[] str = ip.split("\\.");
byte[] IP = new byte[str.length];
for (int i = 0; i < str.length; i++) {
IP[i] = (byte) Integer.parseInt(str[i]);
}
Socket socket = getSocket(InetAddress.getByAddress(IP), port);
if (socket == null) {
Log.i("SO sendFILE","null");
return false;
}
Log.i("SocketOP", "sendFILE-1");
File f = new File(path);
BufferedOutputStream out = new BufferedOutputStream( socket.getOutputStream() );
FileInputStream fileIn = new FileInputStream(f);
Log.i("SocketOP", "sendFILE-2");
byte [] buffer = new byte [1024];
int bytesRead =0;
while ((bytesRead = fileIn.read(buffer)) > 0) {
out.write(buffer, 0, bytesRead);
System.out.println("SO sendFile" + bytesRead);
}
out.flush();
out.close();
fileIn.close();
Log.i("SocketOP", "sendFILE-3");
} catch (IOException e) {
return false;
//e.printStackTrace();
}
// Toast.makeText(this, "Lvbvhhging...", Toast.LENGTH_SHORT).show();
return true;
}
this is how i receive connection and seperate text from file (i concatenate "text" to the output stream for the text)
public ReceiveConnection(Socket socket)
{
this.clientSocket = socket;
this.fileSocket=socket;
SocketOperator.this.sockets.put(socket.getInetAddress(), socket);
}
#Override
public void run() {
try {
// PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
// PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
BufferedReader in = new BufferedReader(
new InputStreamReader(
clientSocket.getInputStream()));
InputStream is=clientSocket.getInputStream();
String inputLine;
while ((inputLine = in.readLine()) != null) {
if (inputLine.contains("Text") == true)
{
appManager.messageReceived(inputLine);
Log.i("SocketOP","text");}
else if
(inputLine.contains("Text") == false)
{
Log.i("SocketOP","filee");
appManager.fileReceived(is);
}
else{
clientSocket.shutdownInput();
clientSocket.shutdownOutput();
clientSocket.close();
fileSocket.shutdownInput();
fileSocket.shutdownOutput();
fileSocket.close();
SocketOperator.this.sockets.remove(clientSocket.getInetAddress());
SocketOperator.this.sockets.remove(fileSocket.getInetAddress());
Log.i("SocketOP", "CLOSING CONNECTION");
}
}
} catch (IOException e) {
Log.e("ReceiveConnection.run: when receiving connection ","");
}
}
}
and this is how i finally receive the file in a service called imService :
public void fileReceived(InputStream is)
throws FileNotFoundException, IOException {
Log.i("IMSERVICE", "FILERECCC-1");
if (is!= null) {
FileOutputStream fos = null;
BufferedOutputStream bos = null;
try {
fos = new FileOutputStream("/sdcard/chats/ffffff.txt");
bos = new BufferedOutputStream(fos);
byte[] aByte = new byte[1024];
int bytesRead = 0;
System.out.println("imService fileReceive" + bytesRead);
while ((bytesRead = is.read(aByte)) != -1) {
bos.write(aByte, 0, bytesRead);
System.out.println("imService fileReceive" + bytesRead);
}
bos.flush();
bos.close();
Log.i("IMSERVICE", "FILERECCC-2");
} catch (IOException ex) {
// Do exception handling
}
}
right where i receive the file connection and forward the inputstream IS to the file receive method, i see that its getting the bytes but once filereceived is called it isnt receving any bytes.
it uses tcp/ip.
ok, try it on your method
public void fileReceived(InputStream is)
throws FileNotFoundException, IOException
{
string result;
FileOutputStream fos = null;
fos = new FileOutputStream("/sdcard/chats/ffffff.txt");
Log.i("IMSERVICE", "FILERECCC-1");
if (is!= null)
{
// result = convertStreamToString(is);
// result = result.replace("\n", "");
// Log.e("InputStream output",result);
//IOUtils.copy(is,fos);
byte[] buffer = new byte[1024];
int length;
while ((length = is.read(buffer)) > 0)
{
fos.write(buffer, 0, length);
}
// Close the streams
fos.flush();
fos.close();
is.close();
}
}
/* public static String convertStreamToString(InputStream is)
throws Exception
{
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
is.close();
return sb.toString();
}
*/
EDIT: make other stuff in fileReceived method as comment.. just paste my suggested code.
EDIT: its a IOUtils from apache use it..

Categories

Resources