Simple Question I know - but my android app simply can´t find my CSV file. I´ve placed the file here:
and access it with this code:
public void getFragenfromCSV(){
AssetManager a = getAssets();
BufferedReader reader = null;
try {
InputStream is = a.open("fragenbronze.csv");
reader = new BufferedReader(new InputStreamReader(s));
} catch (IOException e) {
System.out.println("SSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSS");
e.printStackTrace();
}
try {
String line;
while ((line = reader.readLine()) != null) {
String[] RowData = line.split(",");
System.out.println(RowData[0]);
}
}
catch (IOException ex) {
// handle exception
}
}
On running the app I always get the IOException from the catch part.
you have to place it in
src/main/assets
never put something you want to keep in build/ as this get's removed with clean
Project Structure with assets folder
You are going inside build but actually you have to go inside src/main/assets.
Related
After reading a file, I'm trying to delete it, but the following error appears:
java.io.IOException: Unable to delete file test.zip at
org.apache.commons.io.FileUtils.forceDelete (FileUtils.java:1390) at
org.apache.commons.io.FileUtils.cleanDirectory (FileUtils.java:1044)
at org.apache.commons.io.FileUtils.deleteDirectory
(FileUtils.java:977)
Here is my code. I've been careful to close the InputStream in the finally clause and only then call the method that deletes the file, but even then I can only delete it when I stop the program.
InputStream is = null;
try {
is = new URL(filePath).openStream(); // filePath is a string containing the path to the file like http://test.com/file.zip
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "utf-8"));
String line;
StringBuilder sb = new StringBuilder();
while ((line = reader.readLine()) != null) {
sb.append(line.trim());
}
String xml = sb.toString(); // this code is working, the result of the "xml" variable is as expected
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (is != null) {
is.close();
}
} catch (Exception e) {
e.printStackTrace();
}
removeFileAndFolder(absolutePath);
}
private void removeFileAndFolder(String absolutePath) {
new Thread(new Runnable() {
#Override
public void run() {
try {
String folder = getFolder(absolutePath); // this method just get the path to the folder, because I want to delete the entire folder, but the error occurs when deleting the file
FileUtils.deleteDirectory(new File(folder));
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
}
After some tests I discovered that I can manually delete the file just before the line "is = new URL (filePath) .openStream ();". After it, and even after the line "is.close ();" I can not delete the file manually unless I stop the program.
I got it. I was opening the file by the url (is = new URL(filePath).openStream();), and trying to delete it by absolute path. I changed it to "is = new FileInputStream(absoluteFilePath);" and it works!
I have a custom java server. It uses an external xml config file.
I have some command line options to help the user, the usual stuff for showing a help file, setting ports, etc...
I've recently added a command to generate a default config file for the server. It's an xml file. After researching my options, packing a default xml file in the jar seemed to be the way to go, but I'm obviously missing something.
So far my code looks like this:
public class ResourceLoader {
private File outFile = null;
private Reader fileReader = null;
private Writer fileWriter = null;
private InputStream is = null;
private char[] buffer = null;
public ResourceLoader() {
outFile = new File("default-server.xml");
}
public void generateDefaultServerXml() {
is = ResourceLoader.class.getResourceAsStream("/default-server.xml");
if (is == null) {
System.out.println("Configuraiton File generation failed. The InputStream is null.");
} else {
fileReader = new InputStreamReader(is);
}
buffer = new char[4096];
FileOutputStream fos;
try {
fos = new FileOutputStream(outFile);
fileWriter = new OutputStreamWriter(fos);
while (fileReader.read(buffer) != -1) {
fileWriter.write(buffer, 0, buffer.length);
fileWriter.flush();
buffer = new char[4096];
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
fileReader.close();
fileWriter.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
The code above works perfectly fine when I run it in eclipse, but intitially, after I export the jar file the server could not locate the default-server.xml file when I run the command from the terminal.
The file itself is located in a package called main.resources along with some other config files and the above class.
I have since moved the ResourceLoader.class to another package. After doing that the server seems to find the xml file in the main.resources package (InputStream is not null) but the resulting generated default-server.xml file is empty.
Again, this all works perfectly well when I run it in eclipse, it's only after I export the project and try issue the command from the terminal that the process fails. What am I doing wrong?
The above class is instantiated, and the generateDefaultServerXml() is called, from the main method of the server.
EDIT: My path for writing default-server.xml was slightly wrong. Now that I've adjusted it the code works exactly as expected when I run it in Eclipse. The resource is read in the correct way, and written to the file in the correct location. But it still doesn't work when I try the same thing from the jar file.
You current line ResourceLoader.class.getResourceAsStream("/default-server.xml") means that you are trying to load a resource named default-server.xml from the root of your classpath, or put simpler, from the root of your jar file. This means that xml file should NOT be in any package inside the jar file.
When you assemble your jar file and then run jar tf my.jar on it, do you see your default-server.xml file? Does it reside in some package or in the root of the jar file?
The problem here is since you are packaging the application as a jar. The procedure to call an external resource is quite different.
You need to have a folder structure as
root
--your jar
--your xml file
Your code shallwork if the application is using an default-server.xml file inside the jar.
Otherwise, Replace below line in your code if you want to use an external default xml file.
is = new FileInputStream("./default-server.xml");
If the output file you want at root location the use below code
public ResourceLoader() {
outFile = new File("./default-server.xml");
}
Alternate code as per discussion
public class ResourceLoader {
public void generateDefaultServerXml() {
try {
String defaultxmltext =readFileToString("/default-server.xml");
writeFileFromInputString(defaultxmltext);
} catch (IOException e) {
//exception
}
}
public static void writeFileFromInputString(String everything) throws IOException {
try (BufferedWriter writer = new BufferedWriter(new FileWriter("./default-server.xml"))) {
everything = everything.replaceAll("\n", System.getProperty("line.separator"));
writer.write(everything);
}
}
public static String readFileToString(String path) throws IOException {
String everything = null;
try (BufferedReader br = new BufferedReader(new FileReader(path))) {
StringBuilder sb = new StringBuilder();
String line = br.readLine();
while (line != null) {
sb.append(line);
sb.append(System.lineSeparator());
line = br.readLine();
}
everything = sb.toString();
}
return everything;
}
}
Hope this helps
consider your file located on src/main/resources try this
getClass().getClassLoader().getResource(fileName)
well as far as i can see your main problem is that you are passing the wrong path, since you mentioned the xml is under main.resources you will need to add this to the path when trying to load the file, here is a sample piece of code that should work for you
Scanner sc = null;
PrintWriter writer = null;
try {
sc = new Scanner(getClass().getResourceAsStream("main/resources/server.xml"));
writer = new PrintWriter("./default_server.xml", "UTF-8");
while(sc.hasNextLine()) {
writer.println(sc.nextLine());
}
} catch (Exception e) {
} finally {
if(sc != null) {
sc.close();
}
if(writer != null){
writer.close();
}
}
In one of my application i'm accessing some files in the sd card. I'm using the below function to determine the mounted sd-card path.
File file = new File("/system/etc/vold.fstab");
FileReader fr = null;
BufferedReader br = null;
String path = "";
try {
fr = new FileReader(file);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
try {
if (fr != null) {
br = new BufferedReader(fr);
String s = br.readLine();
while (s != null) {
if (s.startsWith("dev_mount")) {
String[] tokens = s.split("\\s");
path = tokens[2]; //mount_point
}
s = br.readLine();
}
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (fr != null) {
fr.close();
}
if (br != null) {
br.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return path;
This works for all the devices prior to Kitkat. But in Kitkat version i'm getting FileNotFoundException on line 1,
File file = new File("/system/etc/vold.fstab");
I found so many articles about updated sd card permission in Android kitkat version.But still a bit confused about that...
Please can anyone help me to sort it out??? Thanks in advance...
vold.fstab is no longer used in 4.3. Instead, fstab. is now present.
Refer to http://source.android.com/devices/tech/storage/ although it is not very clear
You must call to :
File sdCardPath = Environment.getExternalStorageDirectory();
to know the path of SD card. This function call invoke system operative function wich determine the path of SD card. And to know the state of external storage you must use
Environment.getExternalStorageState()
function.
I have tried many solutions to read files but no one were working.
I need a method to read a system file and show the text in a toast or in a dialog.
Of course my app has root permission.
I have to show the content of "eoc_status" in a toast after a checkbox click.
For example;
Runtime.getRuntime().exec("/sys/kernel/abb-chargalg/eoc_status").getInputStream();
I need to open text files.
Assuming you do have read-access to eoc_status
You are going to want to read it, not exec it. ie use cat or use a FileReader:
Then you will want to do something (put it in your toast) with the returned InputStream.
For example:
BufferedReader buffered_reader=null;
try
{
//InputStream istream = Runtime.getRuntime().exec("cat /sys/kernel/abb-chargalg/eoc_status").getInputStream();
//InputStreamReader istream_reader = new InputStreamReader(istream);
//buffered_reader = new BufferedReader(istream_reader);
buffered_reader = new BufferedReader(new FileReader("/sys/kernel/abb-chargalg/eoc_status"));
String line;
while ((line = buffered_reader.readLine()) != null)
{
System.out.println(line);
}
}
catch (IOException e)
{
// TODO
e.printStackTrace();
}
finally
{
try
{
if (buffered_reader != null)
buffered_reader.close();
}
catch (IOException ex)
{
// TODO
ex.printStackTrace();
}
}
I am newbie in android development. Today for i was trying to display all my practiced programs of java in my application. I want the application to read the data written in .txt file.
In which folder should I store all my programs? They are more than 100.
I want to display the content of program 2 when I clicked the 2 on the list view or any other
Can we store the text files in database? If so how can I access them ? How can I read them?
Any basic ideas how can I solve this?
You can kept text file in raw / assets folder.
To read them just use this code.
From Assets:
BufferedReader reader = new BufferedReader(
new InputStreamReader(getAssets().open("YourTextFile.txt")));
From Raw:
InputStream inputStream = context.getResources().openRawResource(R.id.yourresoureid);
InputStreamReader inputreader = new InputStreamReader(inputStream)
as you are a java programmer no need to tell how to read data from InputStream, if your really want then tell me I will post the rest of the code.
Saving that huge amount of data in data base is not a good idea.
Example to read data from InputStream
BufferedInputStream bis=new BufferedInputStream(inputstream);
ByteArrayBuffer baf=new ByteArrayBuffer(1000);
while((k=bis.read())!=-1)
{
baf.append((byte)k);
}
String results=new String(baf.toByteArray());
Start with something easy and work up to the database option.
Yes, the answer would be quite long, and I think a tutorial on SQLite would be a place to start on this.
2,1. Try putting your text files in the assets folder and reading them like this. This code reads a file, and dumps it line by line into the log.
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_read);
AssetManager assetManager = getAssets();
try {
BufferedReader br = new BufferedReader(new InputStreamReader(
assetManager.open("hi.txt")));
// InputStream inputStream = assetManager.open("hi.txt");
// BufferedReader br = new BufferedReader(
// new InputStreamReader(inputStream));
String lineIn;
while ((lineIn = br.readLine()) != null) {
Log.d("ReadTheDamnFile", lineIn);
}
assetManager.close();
} catch (IOException e) {
}
}
try this its work fine :)
try
{
if(poslist==0)
{
in = this.getAssets().open("file1.txt");
iv.setBackgroundResource(R.drawable.fileimage1);
}
}
catch (IOException e)
{
e.printStackTrace();
}
try {
reader = new BufferedReader(new InputStreamReader(in,"UTF-8"));
} catch (UnsupportedEncodingException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
String line="";
String s ="";
try
{
line = reader.readLine();
}
catch (IOException e)
{
e.printStackTrace();
}
while (line != null)
{
s = s + line;
s =s+"\n";
try
{
line = reader.readLine();
}
catch (IOException e)
{
e.printStackTrace();
}
}
tv.setText(""+s);
}
public void onClick(View v){
try {
line = reader.readLine();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (line != null){
tv.setText(line);
} else {
//you may want to close the file now since there's nothing more to be done here.
}