File Not Found when trying to create a PrintWriter, Android Studio - java

I am trying to edit a file in internal storage (So no permission should be needed, right?), but when I run this code:
String locus = getFilesDir().getAbsolutePath();
File locusfile = new File(locus);
String loglocation = locus + "/log.txt";
File log = new File(loglocation);
if(log.exists())
{
PrintWriter pw = new PrintWriter(log);
}
the PrintWriter pw comes up with "FileNotFoundException".
Why would this occur even when I verify that the file exists?
Thanks.

Try to add log.createNewFile(); after File log = new File(loglocation);.

Related

How can i write to a file when distributable file is launched?

I have program that read from a file. Now I created another task, that aims to update/write this file into same files. My problem now is when I generate my project's distributable file, during running and try to update my file, it does not write/update my changes. If I run it directly on my IDE, it works fine. This is wha I did so far:
private void tbleAddressMouseClicked(java.awt.event.MouseEvent evt) {
if(tbleAddress.getSelectedColumn()==3){
AddressUtil util = new AddressUtil();
List<AddressUtil> lists = util.getAddresses();
Address address = lists.get(tbleAddress.getSelectedRow());
if(tbleAddress.getValueAt(tbleAddress.getSelectedRow(), 0)!=null){
address.setRegion("\""+tbleAddress.getValueAt(tbleAddress.getSelectedRow(), 0).toString()+"\"");
}
lists.set(tbleAddress.getSelectedRow(), address);
try {
FileWriter fw;
fw = new FileWriter("./src/address.csv"); // This is where I doubt, if my **jar** file reads this directory
for(Address a:lists){
fw.append(a.getRegion);
fw.append(",");
fw.append(a.getAddressName());
fw.append("\n");
fw.flush();
}
fw.close();
} ...
My getAddresses is defined as:
public List<Address> getAddresses() {
List<Address> addresses = new ArrayList<>();
BufferedReader br = null;
InputStream in = this.getClass().getResourceAsStream("/address.csv");
BufferedReader reader = null;
try {
reader = new BufferedReader(new InputStreamReader(in));
String line = "";
while((line = reader.readLine())!=null){
String[] result = line.split(",");
Address address = new Address();
address.setRegion(result[0]);
address.setAddressName(result[1]);
addresses.add(address);
}...
My address.csv is of form:
"Region I","Sample St., Sample Address"
"Region II","Sample St., Sample Address 2"
...
Any help is much appreciated
Your issue with writing to the file is most likely due to the relative path you're using when you define the FileWriter. The dot in your path means "current working directory" so if your program is located at path C:\myProgram and you run your program such that it uses this path as the working directory then it's going to look for C:\myProgram\src\address.csv
So depending on the requirements for your program a relative path might be appropriate, in which case you need to determine what the correct path will be and ensure the file exists at that location, or you may to use some other mechanism to find the file.
I also notice that you're using getResourceAsStream to get an InputStream to your file. You should know that this only works if the file is available on the classpath of your program.

how to write to a file when it's an executable in java

HI
I have a problem with writing to files, It works in the program(netbeans), but when it's exported to a jar file, it throws an exception, "FileNotFound." I checked inside the file folder inside the jar, and it was there, I think I need to use streams just as I use them in reading files:
InputStream u= FM.class.getResourceAsStream("/genex/files/data.txt");
try (InputStreamReader f = new InputStreamReader(u)) {what I wrote}
and that works perfectly fine, I just need a method like a getResourceAsStream() for OutputStreams
(btw, FM is the class name)
UPDATE: For those of you who really wanted to write files inside the jar, well, it's impossible. BUT, I found another way to store all of your files:
-writing
File file = new File("/GH/GX/save.txt");
if (!file.exists()) {
file.getParentFile().mkdirs();
file.createNewFile();
}
try (PrintWriter writer = new PrintWriter(file)) {what you want to write}
-reading
File file = new File("/GH/GX/save.txt");
if (!file.exists()) {
return;
}
try (FileReader f = new FileReader(file)) {
//fr = new FileReader(f);
try (BufferedReader br = new BufferedReader(f)) {what you want to read}}
So I hope this article helped you :)
You can only read from files inside a jar not write to them.

Where should Android App data be stored? How should I write to a file?

Where should the CSV output text file from my Android App (writing in Eclipse) be stored. I currently use:
> File peopledetail_file = new File(this.getFilesDir(),
> "PeopleDetailsFile");
and
InputStream filestream = openFileInput("PeopleDetailsFile");
to access my file. This clearly does not work, as I get an error, saying it can't be found at this location
/data/data/com.example.partyorganiser/files/PeopleDetailsFile
For Creating a file you must call peopledetail_file.createNewFile() then write your file
File peopledetail_file = new File(this.getFilesDir(), "PeopleDetailsFile");
peopledetail_file.createNewFile();
FileOutputStream fos = new FileOutputStream(peopledetail_file);
// do writing ...
PrintWriter pw = new PrintWriter(fos);
pw.print("Hello");
pw.flush
fos.flush();
fos.close();
If you are going to use openFileInput(), use openFileOutput().
If you are going to use getFilesDir() for output, use getFilesDir() for input.

Using a PrintWriter and File Object to Write to an Output File

I have a JFileChooser object used to get a data file from the user. What I need to do is create a File object and PrintWriter object so that I can write to a file named "output.txt". The file should be written to the same directory from which the data file was retrieved from.
So far I have tried:
// Write to a text file`
File file = new File ("output.txt");
PrintWriter printWriter = new PrintWriter (f);
This snippet of code creates the output file, but I need to it be written to the same directory from which the data file came from.
First thoughts were to call the .getPath() method (see below) on the JFileChooser object.
String fileDir = inputFile.getPath();
String fileName = "output.txt";
File f = new File (fileDir + "/" + fileName);
PrintWriter printWriter = new PrintWriter (f);
Thoughts?
inputFile.getPath() will get you the file path. You need inputFile.getParent() which will get you the directory of the file.
String fileDir = inputFile.getParent();
String fileName = "output.txt";
File f = new File (fileDir,fileName);
PrintWriter printWriter = new PrintWriter (f);

Android write a file that shows in Downloads app

I am trying to have my app export a .csv file that can be picked up in the download APP. The way I am doing this is through fileoutput
I get remotedir By calling Environment.getExternalStorageDirectory().getAbsolutePath()
* Download CSV
*/
public static void downloadCSV(String filename, String remoteDir) throws Exception{
File dir = new File( remoteDir + "/download/");
dir.mkdirs();
//FileWriter f = new FileWriter("Download/" + filename + ".csv");
File fileObject = new File(dir, filename);
fileObject.delete();
fileObject.createNewFile();
ObjectOutputStream objectOut = null;
FileOutputStream stream = new FileOutputStream(fileObject);
objectOut = new ObjectOutputStream(new BufferedOutputStream(stream));
/* Irrelevant code */
String csv = Helper.getCSV(table.getColumnList(), view);
objectOut.writeChars(csv);
objectOut.close();
}
Whenever I test it on my phone(HTC One S) I don't see the file anywhere. I want my csv file to pop up in the Downloads app, but I'm not sure which directory that represents.
Thanks
You might have to scan the file with the MediaScanner before it will show up, at least that's how you'll be able to see it from your desktop for finding/debugging. See the MediaScanner docs for details.

Categories

Resources