Write to file is not working in Android - java

I have been trying to write to a file in Android. It is not working and it doesn't even create a file. It always executes the catch block. Here is the part of my program.
private void write(){
try {
FileWriter fileWriter = new FileWriter("C:\\Users\\Administrator\\AndroidStudioProjects\\SunCalculator\\app\\src\\main\\res\\raw\\au_locations.txt");
Log.e("Data","path detected");
BufferedWriter bfWriter = new BufferedWriter(fileWriter);
bfWriter.write("Text Data");
bfWriter.close();
Log.e("Data","worked");
} catch (IOException e) {
e.printStackTrace();
Log.e("Data","not worked");
}
}
I also tried to create a File object and passing it to the FileWriter constructor. None of these worked. I am using Android Studio 2.3.3

You are trying to write a file in location C:\\Users.... which is the directory structure of Windows OS.
But Android is built upon Linux OS. To get the user writeable directory in android, you should use Environment.getExternalStorageDirectory() as below:
File file = new File(Environment.getExternalStorageDirectory(), filename);

Related

Eclipse: Can't add a relative path to a .txt file to a Java application

I have a Java web application (running on Tomcat 9.0 on Linux) that retrieves a message (including a unique 4-letter location code), looks up the code in a CSV file and returns a human-readable location name. For example CLLK,Clear Lake.
The application was working well, when I'd loaded the file's absolute path /home/beau/eclipse-workspace/pagerfeed/brigades.csv.
But when I tried to change this to a relative path pagerfeed/brigades.csv, the file couldn't be found. Further investigation found that Eclipse was expecting to find the file at /home/beau/pagerfeed/brigades.csv, completely ignoring my eclipse-workspace folder.
Does anyone know what might be causing this?
Additionally, the file is currently just in the project's root directory, which I assume isn't best practice. Considering it will be deployed as a WAR file, is there somewhere better to put this file? (It can be accessible from the address bar.)
The code to load the file (yes it's messy - the commented lines are other methods I've tried that haven't worked properly):
// The code that actually gets the file (not working)
Brigade.importBrigadesFromFile("pagerfeed/brigades.csv");
// The code, when it WAS working
Brigade.importBrigadesFromFile("/home/beau/eclipse-workspace/pagerfeed/brigades.csv");
// And my background code to read the file
public Iterable<CSVRecord> read(String file) {
Iterable<CSVRecord> records = null;
try {
Reader reader = new FileReader(file);
// InputStream inputStream = getClass().getClassLoader().getResourceAsStream(file);
// InputStream inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream(file);
// BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
records = CSVFormat.DEFAULT.parse(reader);
System.out.println("Found the CSV file!");
} catch (FileNotFoundException fe) {
String absolutePath = new File("/data/testFile").getAbsolutePath();
System.out.println("File was not found.");
System.out.println("Try putting file here: " + absolutePath + ". ");
fe.printStackTrace();
} catch (IOException ioe) {
System.out.println("Unable to parse the CSV file. Details: ");
ioe.printStackTrace();
} catch (NullPointerException ne) {
System.out.println("Could not read file at " + new File("filegoeshere").getAbsolutePath());
System.out.println("InputStream returned null. Details: ");
ne.printStackTrace();
}
return records;
}
Screenshot of my Eclipse path variables: https://imgur.com/a/Gnqrj

Java generate and download csv file

I'm trying to generate and download csv file in a Java project that use an old framework called Echo Studio 3, with Tomcat.
here is my code:
List<Object> reportCount = this.getReport(accountId);
ArrayList<String[]> result = new ArrayList<String[]>();
for (Object list: reportCount) {
String[] rowReport = (String[]) list;
result.add(new String[]{String.valueOf(rowReport[0]),String.valueOf(rowReport[1])});
}
File filename = new File("report.csv");
FileWriter fw = new FileWriter(filename);
fw.append("Name");
fw.append(',');
fw.append("Count");
fw.append('\n');
for (String[] ls: result){
fw.append(ls[0].toString());
fw.append(',');
fw.append(ls[1].toString());
fw.append('\n');
}
try {
fw.flush();
fw.close();
} catch (Exception e) {
System.out.println("Error while flushing/closing fileWriter !!!");
e.printStackTrace();
}
When the code is triggered, nothing happens, and i have no error message. when i run the debug mode, the result is filled with data, and the breakpoint pass throw the flush(), and no error, and the client is not getting the generated file, did I miss something?
You're writing the file to the current working directory, which may be something you don't expect if you're running the program in a container like Tomcat.
Given you've seen the program execute the calls, i'd test that hypothesis by changing the file path to an absolute path, to make sure that the code is actually writing correctly. If it does, then it's just a path issue.
You could also add a call to find the current working directory 1.

Create a text file using PrintWriter

PrintWriter p;
try {
p = new PrintWriter(new FileWriter("xp.mdb"));
} catch (FileNotFoundException e) {
return;
} catch (IOException e) {
return;
}
p.println("mytext");
p.close();
I'm new to Android programming and don't quite understand how writing to files work. I want to create a new file and write some text to it. The above code works on Windows but on Android I just keep getting FileNotFoundException.
How can I make it create the file if it doesn't exist?
You need to put the file in internal storage, external storage, or (on Android 4.4+) removable storage. Passing a bare filename does not work on Android.

Why files created with Java FileOutputStream on Android are visible on my pc throught USB after few ubs reconnectonions (+up to few minutes)

I have code like this:
File file = new File(Environment.getExternalStorageDirectory(), fileName);
FileOutputStream os = null;
try {
os = new FileOutputStream(file);
} catch (FileNotFoundException e) {
System.err.println("Error while creating FileOutputStream");
e.printStackTrace();
}
os.write("something".getBytes());
os.close();
and when i create file on my HTC desire x i have to disconnect usb, wait few minutes, connect it again to see created files in windows explorer. Why it's like that? And how can i prevent it?
And additionaly: when i use ls in terminal on my phone i see this file immediately.
Try calling close() on the FileOutputStream.

How to write content to a file

try {
File file = new File("sample.txt");
FileWriter fw = new FileWriter(file,true);
fw.append('d');
fw.write(100);
fw.close();
} catch(IOException exp) {
exp.printStackTrace();
}
I am unable to append or write anything to the file.
But I could read the content from the file.
Is anything wrong with my code?
It sounds like you probably are writing to a file - but not the file you expect to. If no exceptions have been thrown (and swallowing an exception, just writing it to standard out, is rarely the right approach) then the file will exist somewhere.
It will be in whatever directory the code is running from - which may well not be the same as the directory containing the sample.txt file you're reading. I suggest you explore the file system, and also check the Run Configuration in Eclipse to see what the working directory for the app will be.
As an aside, you should be closing the writer in a finally block so that it gets closed even if there's an exception, like this:
File file = new File("sample.txt");
FileWriter fw = null;
try {
fw = new FileWriter(file, true);
fw.append('d');
fw.write(100);
} catch(IOException) {
// Ideally do something to indicate the failure to the caller
// - do you need to catch this at all?
e.printStackTrace();
} finally {
// From Guava
Closeables.closeQuietly(fw);
}
Obviously you can do this without Guava but it'll make things a lot simpler - and not just here. If you're using Java 7 you can make it even simpler with a try-with-resources statement.
http://www.roseindia.net/java/example/java/io/java-write-to-file.shtml
You can Flush context if code is right and still you are facing problem. it "Flushes the stream"
This link can help!
Like was said before the file may be getting cleared out during the build/clean process. Try specificing an absolute path to the file and running it again. Everything you have written is correct sans the corrections already offered.
try {
File file = new File("C:\sample.txt"); // for Windows or possibly just "/sample.txt" for *nix
FileWriter fw = new FileWriter(file,true);
fw.append('d');
fw.write(100);
} catch(IOException e) {
e.printStackTrace();
} finally {
// Good practice to move close to a finally block
fw.close();
}
You may try using the below syntax :
String filename = "C:/sample.txt";
FileWriter fw = new FileWriter(filename,true);

Categories

Resources