ASCII file in Eclipse plugin project not visible after export - java

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.

Related

Get content from a text file to String (Android) (FileNotFound) (Java)

I want to get the text from a text file I have in my project (android studio) and make that text to a string. I am currently having trouble getting the correct path or something. I'm using two methods I found here on Stackoverflow to get the textfiles to Strings. These are the methods:
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;
}
And I'm calling the methods like this, and I have tried all kinds of pathing but none seems to work:
Log.i("er0r", Solve.getStringFromFile("\\tables\\lowerLayer\\cross\\whiteRed.txt"));
This is just an attempt to print the content of the textfile. I get the following error: java.io.FileNotFoundException: .\tables\lowerLayer\cross\whiteRed.txt: open failed: ENOENT (No such file or directory)
This is how I have ordered my packages:
http://imgur.com/a/rK9R5
How can i fix this? Thanks
EDIT:
public String LoadData(String inFile) {
String str = "";
try{
StringBuilder buf=new StringBuilder();
InputStream json=getAssets().open(inFile);
BufferedReader in=
new BufferedReader(new InputStreamReader(json, "UTF-8"));
while ((str=in.readLine()) != null) {
buf.append(str);
}
in.close();
} catch (Exception e) {
Log.e("er0r", e.toString());
}
return str;
}
Tried this with inFile = "assets\whiteRed.txt"
Got me this error: java.io.FileNotFoundException: assets\whiteRed.txt
ADDITIONAL CODE:
Constructor of the class that's calling the LoadData method
public class Solve {
private Context context;
//constructor
public Solve(Context context){
this.context = context;
}
If at design time, in Android Studio, you want to supply files which your app can read at run time then put them in the assets folder of your Android Studio project.
Maybe you have to create that assets folder first.
After that your app can read those files from assets using assets manager.
Just google for how to do this exactly. All has been posted here many times.

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");

Statically Loading a .txt File

I understand that this question has been asked often before, and yet none of the other answers have worked for me. I am trying to statically load a .txt file in. It works wile inside the compiler (Eclipse) but after I export I get a FileNotFound exception.
I need a method that will take in a file path and load that .txt file statically, and return that file as a String. I think I have to do something with loadRecourceAsStream() but I am not sure.
Here is how I am loading it now:
public static String getFilePath(String path) {
String line = null;
String file = "";
try {
FileReader fileReader = new FileReader(path);
BufferedReader bufferedReader = new BufferedReader(fileReader);
while((line = bufferedReader.readLine()) != null){
file = file + line;
}
bufferedReader.close();
} catch(FileNotFoundException e) {
System.out.println("Unable to open file " + path + "\n");
e.printStackTrace();
} catch(IOException e) {
e.printStackTrace();
}
return file;
}
Here are some other things I have tried. They all work in the compiler but not after exporting:
public static String loadFileAsString(String path){
StringBuilder builder = new StringBuilder();
try{
BufferedReader br = new BufferedReader(new FileReader(path));
String line;
while((line = br.readLine()) != null)
builder.append(line + "\n");
InputStream inputStream = getClass().getClassLoader().getResourceAsStream(path);
br.close();
}catch(IOException e){
e.printStackTrace();
}
return builder.toString();
}
And:
public static String getFile(String path) {
Scanner controlBoard = new Scanner(System.in);
controlBoard = new Scanner(Utils.class.getResourceAsStream(path));
String file = controlBoard.nextLine();
file += "\n" + controlBoard.nextLine();
file += "\n" + controlBoard.nextLine();
return file;
}
And:
public static String getFile(String path) {
System.out.println("test");
StringBuilder out = new StringBuilder();
try {
InputStream in = new FileInputStream(new File(path));
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
String line;
while((line = reader.readLine()) != null) {
out.append(line + "\n");
}
reader.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch(IOException e) {
e.printStackTrace();
}
return out.toString();
}
Any ideas on what I should do?
I think your problem has to be related in how you are running your program when exported as I have taken your code, created a jar, run it and it worked without changing a single line. Well, I have added a main function to be able to run it. I add the code just in case but you will see that the code is the same.
package com.iseji.app.main;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
public class Main {
public static void main (String args[]){
System.out.println(getFilePath(args[0]));
}
public static String getFilePath(String path) {
String line = null;
String file = "";
try {
FileReader fileReader = new FileReader(path);
BufferedReader bufferedReader = new BufferedReader(fileReader);
while((line = bufferedReader.readLine()) != null){
file = file + line;
}
bufferedReader.close();
} catch(FileNotFoundException e) {
System.out.println("Unable to open file " + path + "\n");
e.printStackTrace();
} catch(IOException e) {
e.printStackTrace();
}
return file;
}
}
So the question is how have you imported the file into a jar. You can really just use the "Export to" functionality of your IDE (Eclipse, IntelliJ or whatever). On the other hand I recommend you to use a life-cycle software framework like maven or gradle. Just as an example I show the gradle file that I use to create the jar (but as I say, this is not really important)
apply plugin: 'java'
sourceCompatibility = 1.5
version = '1.0'
repositories {
mavenCentral()
}
dependencies {
testCompile group: 'junit', name: 'junit', version: '4.11'
}
jar {
manifest {
attributes 'Main-Class': 'com.iseji.app.main.Main'
}
}
Anyway how you export your code to a jar, the key is how the Manifest file looks like. You have to be sure that it indicates which is the main class. Verify that it is similar to:
Manifest-Version: 1.0
Main-Class: com.iseji.app.main.Main
In such a way you will be able to run it as normally passing as a parameter the file to read
java -jar ReadingFile-1.0.jar ../../src/main/resources/sample.txt
As I said at the beginning your code is fine. Just double check how you are exporting the code and running it

Sonar: visitFile(): How to get the source code file

I'm implementing custom script rule plugin for Sonar.
I want to make a checking rule directly for the source code
and not from checking tokens or nodes of the ASTtree.
Having the follow code:
#Override
public void visitFile() {
BufferedReader br = null;
File file = null;
String line = null;
try {
file = this.getSourceCode().getFile();
br = new BufferedReader(new FileReader(file));
while ((line = br.readLine()) != null) {
...
}
}
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
My problem is that the :
this.getSourceCode().getFile();
returns back null
how can I get the instance of the file for which was actually the visitFile() called?
How does 'visitFile()' works actually?

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

Categories