Android - Reading text File from Application subclass - java

I have a method in a subclass of Application that needs to read information from a text file. I have used this method in a subclass of Activity and it worked fine.
InputStream is = this.getResources().openRawResource(R.raw.elements);
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
String str = reader.readLine();
However this gives a null pointer exception if I use this code in the Application subclass.
the text file is in the res/raw folder.

private String readTxt() {
InputStream inputStream = getResources().openRawResource(R.raw.elements);
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
int i;
try {
i = inputStream.read();
while (i != -1) {
byteArrayOutputStream.write(i);
i = inputStream.read();
}
inputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return byteArrayOutputStream.toString();
}
Works Perfectly, Source : Display text file in /res/raw

Related

Create and edit a File object in java without physically writing to hard disc

I am trying to create and edit a text file object in java. But once I execute the code, it is physically writing the file in root folder from which the program being executed. How can I do the same without physically writing the text file to hard disc?
File file = new File("tempFile.txt"); // Now the file is not created physically
writeIntoFile(file, listOfString); // After this, the file is created in disc
private static void writeIntoFile(File file, List<String> contents) {
Writer output;
try {
output = new BufferedWriter(new FileWriter(file.getPath(), true));
for (String content : contents) {
output.append(content);
output.append("\r\n");
}
output.close();
} catch (Exception e) {
e.printStackTrace();
}
}
Thanks #Gerome Tahud. The below code did the trick!
private static byte[] writeIntoFile(List<String> contents) {
try {
if (null != contents && contents.size() > 0) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
for (String content : contents) {
content = content + "\r\n";
InputStream inputStream = new ByteArrayInputStream(content.getBytes());
byte[] buffer = new byte[8192];
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) != -1) {
baos.write(buffer, 0, bytesRead);
}
}
return baos.toByteArray();
}
} catch (IOException e) {
e.printStackTrace();
}
return null;
}

Trying to read Text File from Uri Android

I created an android file chooser that returns the uri of a text file. I want to open and read the file and store it's data.My code is:
private void covertFile(Uri data) {
InputStream inputStream = getContentResolver().openInputStream(data);
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
String myText = "";
int in;
try {
in = inputStream.read();
while (in != -1)
{
byteArrayOutputStream.write(in);
in = inputStream.read();
}
inputStream.close();
myText = byteArrayOutputStream.toString();
}catch (IOException e) {
e.printStackTrace();
}
myTextView.setText(myText);
}
But the line InputStream inputStream = getContentResolver().openInputStream(data); givesjava.Io.FileNotFoundException. How do I resolve this?
EDIT: Issue Resolved
First create file object
String path = data.toString();
File file = new File(path);
Now pass the file object as arg in InputStream
InputStream inputStream = getContentResolver().openInputStream(file);

Loading text file gives an error with path

I want to read a text file. For this I am giving a path of the file but its not getting read.
Giving error like : ClassLoader referenced unknown path: /data/app/com.kiranaapp-1/lib/arm
I have saved the text file in helper folder of an app.
public void ReadFile() {
try {
BufferedReader in = new BufferedReader(new FileReader("E:/siddhiwork/KiranaCustomerApp/app/src/main/java/com/kiranacustomerapp/helper/itemNames.txt"));
String str;
List<String> list = new ArrayList<String>();
while ((str = in.readLine()) != null) {
list.add(str);
}
String[] stringArr = list.toArray(new String[0]);
}
catch (FileNotFoundException e)
{
System.out.print(e);
}
catch (IOException e)
{
System.out.print(e);
}
}
As I debug to see if file is getting read and strings are stored in an array,
but nothing happens.
Help please , Thank you..
Edit :
My attempt to get strings in list, not getting any value in itemList
public class StartupActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
List<String> itemList = new ArrayList<>();
itemList = readRawTextFile(StartupActivity.this);
}
public static List<String> readRawTextFile(Context context) {
String sText = null;
List<String> stringList;
try{
InputStream is = context.getResources().openRawResource(R.raw.item_names);
//Use one of the above as per your file existing folder
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
sText = new String(buffer, "UTF-8");
stringList = new ArrayList<String>(Arrays.asList(sText.split(" ")));
System.out.print(stringList);
} catch (IOException ex) {
ex.printStackTrace();
return null;
}
return stringList;
}
}
You should not give a file path to the computer path. Store file either in assets folder or in raw folder then fetch from there in android.
public String loadTextFromFile() {
String sText = null;
try {
//If your file is in assets folder
InputStream is = getAssets().open("file_name.txt");
//If your file is in raw folder
InputStream is = getResources().openRawResource(R.raw.file_name);
//Use one of the above as per your file existing folder
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
sText = new String(buffer, "UTF-8");
} catch (IOException ex) {
ex.printStackTrace();
return null;
}
return sText;
}
To split text with "," format:
String[] sTextArray = sText.replace("\"", "").split(",");
List<String> stringList = new ArrayList<String>(Arrays.asList(sTextArray));
First of all, Put the file in raw directory under res directory.
Now try below code to read file,
public static String readRawTextFile(Context ctx, int resId) {
InputStream inputStream = ctx.getResources().openRawResource(resId);
InputStreamReader inputreader = new InputStreamReader(inputStream);
BufferedReader buffreader = new BufferedReader(inputreader);
String line;
StringBuilder text = new StringBuilder();
ArrayList<String> lineList = new ArrayList<>();
try {
while (( line = buffreader.readLine()) != null) {
text.append(line);
lineList.add(line);
text.append('\n');
}
} catch (IOException e) {
return null;
}
// Use your arraylist here, since its filled up.
return text.toString();
}
If the file is generated dynamically in cache, you can
File file = getCacheDir() + "FOLDER_PATH_WITH_FILENAME";
Otherwise, save the file in assets folder inside main directory.
main
-----> java
-----> res
-----> assets
-----> AndroidManifest.xml
then, get file using:
InputStream inputStream = getAssets().open("FILE_NAME");

How to write a database to a text file in android

I am working on a Spying application for my college project purpose. For that i have logged the Calls, Location and SMS of the device and stored them in a database. Now i want to export the contents of the database to a text file.. I tried the below code.
private void readAndWriteCallsData() {
File dataBaseFile = getDatabasePath("DATABASE");
File callDataFile = new File(Environment.getDataDirectory()+"/data/com.example.myapp/databases/"+"DATABASE");
try {
BufferedReader dbFileReader = new BufferedReader(new FileReader(callDataFile));
String eachLine;
while((eachLine = dbFileReader.readLine()) != null)
{
Callslog.append(eachLine);
Callslog.append("\n");
}
} catch (IOException e) {
e.printStackTrace();
}
}
But that is not working... Please help me...
You can encode the database file from binary stream to character stream by Base64, then decode the text when nessesary.
First find a Base64 library. You can use http://sourceforge.net/projects/iharder/files/base64/. There's only one file, "Base64.java".
Code example:
private void readAndWriteCallsData() {
File callDataFile = new File(Environment.getDataDirectory()+"/data/com.example.myapp/databases/"+"DATABASE");
try {
FileInputStream fis = new FileInputStream(callDataFile);
try{
byte[] buf = new byte[512];
int len;
while((len = fis.read(buf)) > 0){
String text = Base64.encodeBytes(buf, 0, len); // encode binary to text
Callslog.append(text);
Callslog.append("\n");
}
}finally{
fis.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
To revert it, code like following:
private void revertCallsData() {
File encodedCallDataFile; // get reference to the encoded text file
try {
BufferedReader br = new BufferedReader(new FileReader(encodedCallDataFile));
try{
String line;
while((line = br.readLine()) != null){
byte[] bin = Base64.decode(line); // decode each line to binary, you can get the original database file
}
}finally{
br.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
ok guys after a lot of hit and trial i finally found the solution, here is the code, i saved the functionality in a button.
final String SAMPLE_DB_NAME = "MyDBName.db";//database name
save.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
File sd = Environment.getExternalStorageDirectory();
File data = Environment.getDataDirectory();
FileChannel source=null;
FileChannel destination=null;
String currentDBPath = "/data/"+ "your package name" +"/databases/"+SAMPLE_DB_NAME;
String backupDBPath = SAMPLE_DB_NAME;
File currentDB = new File(data, currentDBPath);
File backupDB = new File(sd, backupDBPath);
try {
source = new FileInputStream(currentDB).getChannel();
destination = new FileOutputStream(backupDB).getChannel();
destination.transferFrom(source, 0, source.size());
source.close();
destination.close();
Toast.makeText(getApplicationContext(),"Your database has been exported",
Toast.LENGTH_LONG).show();
} catch(IOException e) {
e.printStackTrace();
}
}
});
the database will be saved in /storage/emulated/0/
I would recommend to export into a structered file format such as JSON or CSV. Here is my JSON exporter method. Maybe it helps
private static final String LOG_FOLDER = "/ExportFolder";
private static final String FILE_NAME = "export_file.json";
public static void exportMeasurementsJSON(Handler mHandler) {
sendToastMessage("Export to JSON started", mHandler);
File folder = new File(Environment.getExternalStorageDirectory()
+ LOG_FOLDER);
if (!folder.exists())
folder.mkdir();
final String filename = folder.toString() + "/"
+ getLogFileName(".json");
try {
FileWriter fw = new FileWriter(filename, false /* append */);
// get the db
SomeDateSource db = PIApplication.getDB();
// Google Gson for serializing Java Objects into JSON
Gson mGson = new GsonBuilder().create();
Cursor c = db.getAllRows();
if (c != null) {
while (c.moveToNext()) {
fw.append(mGson.toJson(new DBEntry(c
.getString(1), c.getString(2), c
.getDouble(3), c.getLong(4))));
fw.append('\n');
}
c.close();
}
fw.close();
sendToastMessage("Export finished", mHandler);
} catch (Exception e) {
sendToastMessage("Something went wrong", mHandler);
e.printStackTrace();
}
}
If you're interested I can also add my CSV exporter.
Your question is not that clear (Are you trying to copy the file to an alternative location or export the actual data from it?)
If you only wish to copy the file, you can copy the db file using the following method:
public static void copyFile(String sourceFileFullPath, String destFileFullPath) throws IOException
{
String copyFileCommand = "dd if=" + sourceFileFullPath + " of=" + destFileFullPath;
Runtime.getRuntime().exec(copyFileCommand);
}
Simply call that method with your database file path (/data/data/package_name/databases/database_name) as sourceFileFullPath and your target file path as destFileFullPath. You can than use tools such as SQLite Expert to view the content of the database on your PC/Laptop.
If your intention is to export the data from the database and store it in a text file (a CSV file or anything similar), then you should not read the database file content, and instead use the SQLiteDatabase class to query each table contents into a Cursor and iterate it to write each cursor row into a text file.
You could export the entire db into your sdcard folder and then use SQLite manager to open and see it's content.
A Example is available here: http://www.techrepublic.com/blog/software-engineer/export-sqlite-data-from-your-android-device/
Here is the complete method for writing the Database in the SD Card:
/**
* Copy the app db file into the sd card
*/
private void backupDatabase(Context context) throws IOException {
//Open your local db as the input stream
String inFileName = "/data/data/yourappPackageName/databases/yourDBName.db";
// OR use- context.getFilesDir().getPath()+"/databases/yourDBName.db";//
File dbFile = new File(inFileName);
FileInputStream fis = new FileInputStream(dbFile);
String outFileName = Environment.getExternalStorageDirectory()+"/"+SQLiteDataHelper.DB_NAME;
//Open the empty db as the output stream
OutputStream output = new FileOutputStream(outFileName);
//transfer bytes from the inputfile to the outputfile
byte[] buffer = new byte[1024];
int length;
while ((length = fis.read(buffer))>0){
output.write(buffer, 0, length);
}
//Close the streams
output.flush();
output.close();
fis.close();
}
Hope it will help you.
One way to do this (I assume its a long procedure, easy one though), if you know the database and get all the tables and retrieve info from those tables. Since, we are talking about sqlite DBs, I assume it will be small.
SELECT * FROM dbname.sqlite_master WHERE type='table';

How to read data written to a file from one android application using another android application

I used following method to write data to a file in one android application
private void writeFileToInternalStorage() {
String eol = System.getProperty("line.separator");
BufferedWriter writer = null;
try{
writer = new BufferedWriter(new OutputStreamWriter(openFileOutput("myFile.txt", MODE_WORLD_WRITEABLE|MODE_WORLD_READABLE)));
writer.write("Hello world!");
}
catch (Exception e)
{
e.printStackTrace();
}
finally
{
if (writer != null)
{
try
{
writer.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
}
Then I tried to read that file from another android application using this method
private void readFileFromInternalStorage(){
String eol = System.getProperty("line.separator");
BufferedReader input = null;
try
{
input = new BufferedReader(new InputStreamReader(openFileInput("myFile1.txt")));
String line;
StringBuffer buffer = new StringBuffer();
while ((line = input.readLine()) != null)
{
buffer.append(line + eol);
}
TextView tv = (TextView) findViewById(R.id.textView);
tv.setText(buffer.toString().trim());
}
catch (Exception e)
{
e.printStackTrace();
}
finally
{
if (input != null)
{
try
{
input.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
}
Second method can't read the file. I added read write permissions also, but it shows only blank screen. What can be the error and how can I correct that ??. I'm new to Android programming and need your help.
Thanks!
The problem is
openFileOutput("myFile.txt", MODE_WORLD_WRITEABLE|MODE_WORLD_READABLE))
The documentation says:
This file is written to a path relative to your app within the
So the case is you are writing file in path relative to application 1 and trying to read it from
path relative to application 2.
You should be able to call Environment.getExternalStorageDirectory() to get the root path to the SD card and use that to create a FileOutputStream. From there, just use the standard java.io routines.
Look below snippet to write file to SD card.
private void writeToSDCard() {
try
{
File file = new File(Environment.getExternalStorageDirectory(),
"filename");
BufferedWriter writer = new BufferedWriter(new FileWriter(file));
writer.write("Hello World");
writer.close();
} catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Look below snippet to read file saved on SD card.
private void readFileFromSDCard() {
File directory = Environment.getExternalStorageDirectory();
// Assumes that a file article.rss is available on the SD card
File file = new File(directory + "/article.rss");
if (!file.exists()) {
throw new RuntimeException("File not found");
}
Log.e("Testing", "Starting to read");
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader(file));
StringBuilder builder = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
builder.append(line);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
Your best bet is to place it into the scdcard into something like /sdcard/Android/data/package/shared/

Categories