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");
Related
I'm new here and i would like to ask on how properties can work with the java codes i mean the values inside of the properties will be use as variables. For example i have file1.txt and file2.txt inside config.properties and store it in an Arraylist then scan the folder and if the files are found copy it. My work only shows the names of the data from the properties that is stored in the arraylist but my another problem is how these data will be copied to another folder.
so far this is my code
public class MainClass {
static Properties prop = new Properties();
static InputStream input = null;
static String filename = "";
public static void main(String[] args) throws IOException {
File source = new File("D:/ojt");
File dest = new File("D:/ojt/New folder");
Properties prop = new Properties();
InputStream input = null;
try {
// getFiles(filename);
} catch (IOException ex) {
ex.printStackTrace();
} finally {
if (input != null) {
try {
input.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
private static void copyFileUsingStream(File source, File dest) throws IOException {
InputStream is = null;
OutputStream os = null;
try {
is = new FileInputStream(source);
os = new FileOutputStream(dest);
byte[] buffer = new byte[1024];
int length;
while ((length = is.read(buffer)) > 0) {
os.write(buffer, 0, length);
}
} finally {
is.close();
os.close();
}
}
private static void copy(String fromPath, String outputPath)
{
// filter = new FileTypeOrFolderFilter(fileType);
File currentFolder = new File(fromPath);
File outputFolder = new File(outputPath);
scanFolder(currentFolder, outputFolder);
}
private static void getFiles(String path) throws IOException{
//Put filenames in arraylist<string>
String filename = "bydatefilesdir.props";
input = MainClass.class.getClassLoader().getResourceAsStream(filename);
Scanner s = new Scanner(input);
File dir = new File(path);
final ArrayList<String> list = new ArrayList<String>();
while (s.hasNextLine()){
list.add(s.nextLine());
}
// ArrayList<String> filenames = new ArrayList<String>();
// for(File file : dir.listFiles()){
// filenames.add(file.getName());
// }
prop.load(input);
//Check if the files are in the arraylist
for (int i = 0; i < list.size(); i++){
String s1 = list.get(i);
System.out.println("File "+i+" : "+s1);
}
System.out.println("\n");
}
private static void copyFileUsingStream(File source, File dest) throws IOException {
InputStream is = null;
OutputStream os = null;
try {
is = new FileInputStream(source);
os = new FileOutputStream(dest);
byte[] buffer = new byte[1024];
int length;
while ((length = is.read(buffer)) > 0) {
os.write(buffer, 0, length);
}
} finally {
is.close();
os.close();
}
}
private static void copy(String source, String dest)
{
// filter = new FileTypeOrFolderFilter(fileType);
File currentFolder = new File(source);
File outputFolder = new File(dest);
scanFolder(currentFolder, outputFolder);
}
private static void scanFolder(File source, File dest)
{
System.out.println("Scanning folder [" + source.toString() + "]...\n");
File[] files = source.listFiles();
for (File file : files) {
if (file.isDirectory()) {
scanFolder(source, dest);
} else {
try {
copyFileUsingStream(source, dest);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
PS: sorry for the poor programming just new in java.. still learning
Edited: I've included the updated codes above..
I suppose java.util.Properties has build in methods to achieve what you are trying.
please refer this example and you will find a better solution.
public class App {
public static void main( String[] args ){
Properties prop = new Properties();
InputStream input = null;
try {
String filename = "config.properties";
input = App.class.getClassLoader().getResourceAsStream(filename);
if(input==null){
System.out.println("Sorry, unable to find " + filename);
return;
}
//load a properties file from class path, inside static method
prop.load(input);
//get the property value and print it out
System.out.println(prop.getProperty("file1.txt"));
System.out.println(prop.getProperty("file2.txt"));
} catch (IOException ex) {
ex.printStackTrace();
} finally{
if(input!=null){
try {
input.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
Am am working on an Eclipse plugin project. Inside that project I have a folder resources, which contains a simple ASCII file, which contains lines with Strings. These Strings are used in a drop down menu, by the ui. If I run a new launchtime Eclipse everything works like it should and the file content is successfully used by the drop down menu but if I export the application and run it, the drop down menu is empty, which means, that the file can't be read.
Inside the plugin.xml (Build tab) I've marked the resource folder (which contains the ASCII file) in the binary build.
This is how I extract the file line by line:
public class ParameterExtractor {
private final static String FILE_PATH = "/resources/parameters";
public ArrayList<String> extractParameters() throws IOException {
ArrayList<String> params = new ArrayList<String>();
URL url = FileLocator.resolve(getClass().getResource(FILE_PATH));
URI uri = null;
try {
uri = url.toURI();
} catch (URISyntaxException e) {
e.printStackTrace();
}
if (uri != null) {
try {
File file = new File(uri);
FileReader fileReader = new FileReader(file);
BufferedReader bufferedReader = new BufferedReader(fileReader);
String line;
while ((line = bufferedReader.readLine()) != null) {
params.add(line);
}
fileReader.close();
} catch (Exception ioe) {
ioe.printStackTrace();
}
}
return params;
}
}
And this is how I use the returned ArrayList:
ArrayList<String> params = new ArrayList<String>();
try {
params = new ParameterExtractor().extractParameters();
} catch (IOException e1) {
e1.printStackTrace();
}
final Combo combo = new Combo(container, SWT.BORDER);
combo.setItems(params.toArray(new String[params.size()]));
What could cause the problem and how can I solve it?
I would be grateful for any help!
FileLocator.resolve does not guarantee to return you a URL than can be used to read a file. Instead use:
Bundle bundle = ... your plugin bundle
URL url = FileLocator.find(bundle, new Path(FILE_PATH), null);
url = FileLocator.toFileURL(url);
The URL returned by toFileURL is suitable for reading using File and FileReader.
I want read files in a directory. I want add in:
List<String> nomi = new ArrayList<String>();
the linestring of file Nomi.txt.
With debug i view correctly the files in links(001.jpg 002.jpg 003.jpg) and ft(Nomi.txt), but in stream i have always null;
InputStream stream = f.retrieveFileStream(/*url_ftp + "/photo/"+ft*/ft);
my complete code is this:
private static abstract class GetLinksTask extends AsyncTask<String, Void, List<String>> {
protected List<String> doInBackground(String... urls) {
List<String> links = new ArrayList<String>();
String ft=null;
BufferedReader reader = null;
List<String> nomi = new ArrayList<String>();
FTPClient f = new FTPClient();
try {
int reply;
f.connect(url_ftp);
f.login(username,password );
reply = f.getReplyCode();
if (!FTPReply.isPositiveCompletion(reply)) {
f.disconnect();
System.err.println("FTP server refused connection.");
}
FTPListParseEngine engine = f.initiateListParsing("photo");
while (engine.hasNext()) {
FTPFile[] files = engine.getNext(25); // "page size" you want
//FTPFile[] files = engine.getFiles(filter);
for (FTPFile file : files) {
if(file.getName().substring(file.getName().length()-3,file.getName().length()).equals("jpg")){
System.out.println(file.getName());
links.add(file.getName());
}else{
ft=file.getName();
InputStream stream = f.retrieveFileStream(/*url_ftp + "/photo/"+ft*/ft);
reader = new BufferedReader(new InputStreamReader(stream, "UTF-8"));
//nomi.add(reader.readLine());
}
System.out.println(file.getName());
}
//names=nomi;
}
}catch (IOException e) {
e.printStackTrace();
}finally {
if (reader != null)
try {
reader.close();
}catch (IOException logOrIgnore) {
}
}
return links;
}
protected abstract void postExecute(List<String> links);
protected void onPostExecute(List<String> lists) {
postExecute(lists);
}
}
Some tips?
thanks
It is not enough to create a Reader
reader = new BufferedReader(new InputStreamReader(stream, "UTF-8"));
and to close it:
reader.close();
Somewhere, in between, you'll actually have to read the data:
String line;
while( (line = reader.readLine()) != null ){
nomi.add( line );
}
I am explaining the full code of getting inputStream from FTP server and then how to read data from that inputstream. I am assuming, you are using TLS/SSL security layer.
public FTPSClient makeFTPConnection(String vserver, int vport, String vuser, String vpassword) {
LOGGER.debug("ENTRY");
try {
ftpClient = new FTPSClient();
} catch (NoSuchAlgorithmException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
ftpClient.connect(vserver, vport);
ftpClient.login(vuser, vpassword);
ftpClient.execPBSZ(0);
ftpClient.execPROT("P");
ftpClient.changeWorkingDirectory("/");
ftpClient.changeWorkingDirectory("/feeds");
ftpClient.enterLocalPassiveMode();
ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
} catch (Exception e) {
LOGGER.error(e.getMessage());
}
/* // int reply=ftpClient.getReply();
String replyStr=ftpClient.getReplyString();
ftpClient.getAuthValue();*/
LOGGER.debug("EXIT");
return ftpClient;
}
Then after making the connection, we will check weather file exist at ftp or not.
public InputStream checkWOFileExistAtFTP(FTPSClient ftpClient, String host,String user, String filePath) throws IOException {
int returnCode;
// filePath="ftp://"+user+"#"+host+"/"+filePath;
InputStream inputStream = ftpClient.retrieveFileStream(filePath);
String dd=ftpClient.getReplyString();
returnCode = ftpClient.getReplyCode();
if (inputStream == null || returnCode == 550) {
return null;
}
return inputStream;
}
Now we already got the inputStream in above method now its time to read data from it.
BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));
System.out.println("Reading file start.");
char[] charBuffer = new char[8 * 1024];
StringBuilder builder = new StringBuilder();
int numCharsRead;
while ((numCharsRead = br.read(charBuffer, 0, charBuffer.length)) != -1) {
builder.append(charBuffer, 0, numCharsRead);
}
//will print all data
system.out.println(builder.toString());
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';
So I am attempting to read from a file in android. I initialize everything yet I still get a NullPointerException. Am I missing something?
Error is recieved at line 25.
public class Read {
private ArrayList<String> contents;
private final String filename = "saves/user.txt";
public Read(Context context) {
try {
contents = new ArrayList<String>();
InputStream in = context.getAssets().open(filename);
if (in != null) {
// prepare the file for reading
InputStreamReader input = new InputStreamReader(in);
BufferedReader br = new BufferedReader(input);
String line = br.readLine();
while (line != null) {
contents.add(line);
}
in.close();
}else{
System.out.println("It's the assests");
}
} catch (IOException e) {
System.out.println("Couldn't Read File Correctly");
}
}
public ArrayList<String> loadFile() {
return this.contents;
}
}
Do like this
while ((line=reader.readLine()) != null)
{
contents.add(line);
}