how to read files from Internal Storage - java

Iam new to android programming
this code is giving FilenotFound Exception
and going through catch block
where should i save my .txt file.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myCOde=findViewById(R.id.code);
String filename="bully rap.txt";
try {
readCode(filename);
} catch (Exception e) {
myCOde.setText("file not found");
}
}
private void readCode(String filename) throws Exception{
File filesDir=MainActivity.this.getFilesDir();
File myFile=new File(filesDir,filename);
BufferedReader br = new BufferedReader(new FileReader(myFile));
String st;
StringBuilder code= new StringBuilder("hello");
while ((st = br.readLine()) != null){
code.append(st);
myCOde.setText(code);
}

Using below code is not gonna help you to achieve what you want.
File filesDir = MainActivity.this.getFilesDir();
Above code usually returns the path where /data/data/{your package name}/files. If you want to access an external file directory, as in you case like Download folder you should use something like below.
String filesDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
Furthermore if you are going to write to an external file directory, you may need to add neccessary permissions in the manifest.xml

Related

Error reading file in a jar

I'm trying to read a file in java, when I run the program through the IDE it works fine but when it tries to open it when I execute the jar it says the file does not exist. Here is the code where it fails.
public class Main {
public static void main(String[] args) {
try {
App app = new App("files/" + "jsonFile.json", printWriter);
app.runApp();
} catch (Exception e) {
logger.error("error", e);
}
}
}
public class App {
public void runApp(){
File fileDescription = new File("./" + pathDescription);
StringBuilder allDescription = new StringBuilder();
try {
FileReader fr = new FileReader(fileDescription);
BufferedReader br = new BufferedReader(fr);
String line = "";
while ((line = br.readLine()) != null) {
allDescription.append(line);
}
JSONDescription = allDescription.toString();
fr.close();
br.close();
} catch (IOException e) {
logger.error("Error reading file",e);
}
}
}
I know the file exists inside the jar because I looked manually into the jar using jarzilla. Any idea of what it could be happening.
You can lookup a file inside a jar using something like this:
InputStream stream = ClassInsideTheJar.class.getResourceAsStream("/files/jsonFile.json");
BufferedReader br = new BufferedReader(new InputStreamReader(stream));
Where "ClassInsideTheJar" is any class in the jar.
To access files within the JAR, you could use something like
BufferedReader reader = new BufferedReader(new InputStreamReader(
this.getClass().getResourceAsStream("files/jsonFile.json")));
This assumes that there is a folder called files in the root of your jar, and inside that you have the jsonFile.json file.
When you run the program inside an IDE, the compiled code exists outside the jar, in the file system. The IDE compile the code, and then run the program, without building the JAR file. So, your program found the file, because that file still exists in the file system.
To open a file inside a JAR, you need to use another API: loading the file as a resource.
load file within a jar

Android - java.io.FileNotFoundException: /storage/emulated/0/Notes/File.txt: open failed: ENOENT (No such file or directory)

I found lot of topics with the same problem, but they couldn't fix mine.
I initially write a file as follow:`
File root = new File(Environment.getExternalStorageDirectory(), "Notes");
if (!root.exists()) {
root.mkdirs();
}
File notefile = new File(root, sFileName);
FileWriter writer = null;
try {
writer = new FileWriter(notefile);
} catch (IOException e1) {
e1.printStackTrace();
}
try {
writer.append(sBody);
} catch (IOException e1) {
e1.printStackTrace();
}
try {
writer.flush();
} catch (IOException e1) {
e1.printStackTrace();
}
try {
writer.close();
} catch (IOException e1) {
e1.printStackTrace();
}
Don't worry about the try and catch blocks, i will clear them later :D.
And this is the reader which should works in the same directory ("Notes" of the sdcard, if it doesn't exist, will be created), read the file, and put it on a Notify as you can see:`
File root = new File(Environment.getExternalStorageDirectory(), "Notes");
if (!root.exists()) {
root.mkdirs();
}
File file = new File(root, "Nota.txt");
//Read text from file
text = new StringBuilder();
try {
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
while ((line = br.readLine()) != null) {
text.append(line);
text.append('\n');
}
br.close() ;
}catch (IOException e) {
e.printStackTrace();
}
I really don't understand why i get this problem, i even try with
getExternalStorageDirectory().getAbsolutePath()
but without success.
Can someone help me?
You've tried to check with a debugger if root exists when you do:
File root = new File(Environment.getExternalStorageDirectory(), "Notes");
if (!root.exists()) {
root.mkdirs();
}
I do not think it will create the folder when you write the file
To write a file in external storage,
you need to have WRITE_EXTERNAL_STORAGE permission enabled.
Why are you trying to write a file in external storage?
I mean if you want this file for your app only means, use context.getExternalDirs() to get your app's sandbox, it doesn't require write permission, above android 4.2(Jelly bean).
If you want to share the file to other apps, you're doing the right job.
And before writing the file, check whether external storage is mounted programmatically.
Problem Solved
I used SharedPreferences of Android.
I stored the data in MainActivity and take in in my Class as follow:
MainActivity
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = prefs.edit();
editor.putString("string_id", InputString); //InputString: from the EditText
editor.commit();
In my Class to get my data
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
String data = prefs.getString("string_id", "no id"); //no id: default value

How can I load an xml resource file from within an executible Jar file and save it to the folder the jar is located in?

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

Where is the folder for assets?

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.

Saving file as a different name

I have a Java form in which you can select a file to open. I have that file:
File my_file = ...
I want to be able to save my file as a different name.
how can I do it using "File my_file"?
I tried:
File current_file = JPanel_VisualizationLogTab.get_File();
String current_file_name = current_file.getName();
//String current_file_extension = current_file_name.substring(current_file_name.lastIndexOf('.'), current_file_name.length()).toLowerCase();
FileDialog fileDialog = new FileDialog(new Frame(), "Save", FileDialog.SAVE);
fileDialog.setFile(current_file_name);
fileDialog.setVisible(true);
But that doesn't save the file.
I would recommend using the Apache Commons IO library to make this task easier. With this library, you could use the handy FileUtils class that provides many helper functions for handling file IO. I think you would be interested in the copy(File file, File file) function
try{
File current_file = JPanel_VisualizationLogTab.get_File();
File newFile = new File("new_file.txt");
FileUtils.copyFile(current_file, newFile);
} catch (IOException e){
e.printStackTrace();
}
Documentation
If you want to copy it with a different name, i found this piece of Code via google
public static void copyFile(File in, File out) throws IOException {
FileChannel inChannel = new FileInputStream(in).getChannel();
FileChannel outChannel = new FileOutputStream(out).getChannel();
try {
inChannel.transferTo(0, inChannel.size(), outChannel);
} catch (IOException e) {
throw e;
} finally {
if (inChannel != null)
inChannel.close();
if (outChannel != null)
outChannel.close();
}
}
now you can call it with
File inF = new File("/home/user/inputFile.txt");
File outF = new File("/home/user/outputFile.txt");
copyFile(inF, outF);
it´s just important that both Files exist, otherswise it will raise an exception
You can rename the file name.
Use:
myfile.renameTo("neeFile")
There is a Method called renameTo(new File("whatever you want")); for File Objects

Categories

Resources