Java generate and download csv file - java

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.

Related

Text File Writing Not Working

I have been experimenting with writing to text files for output instead of System.out.println(). When I try this, though, nothing seems to be written. What is the issue with my code?
try{
List<String> lines = Arrays.asList("Data Goes Here");
Path file = Paths.get("output.txt");
Files.write(file, lines, Charset.forName("UTF-8"));
}
catch (IOException ex) {
System.out.println("Frick, something broke. Sorry folks, go home.");
}
I just did a small change to your code by passing the path as the resources directory located in the root of my project. I was able to write to the file successfully.
Here is the updated code:
try {
List<String> lines = Arrays.asList("Data Goes Here");
Path file = Paths.get("./resources/test.txt");
Files.write(file, lines, Charset.forName("UTF-8"));
}
catch (IOException ex) {
ex.printStackTrace();
System.out.println("Frick, something broke. Sorry folks, go home.");
}

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

Check if file exists from string

This is the code I use when I try to read some specific text in a *.txt file:
public void readFromFile(String filename, JTable table) {
BufferedReader bufferedReader = null;
try {
bufferedReader = new BufferedReader(new FileReader(filename));
String a,b,c,d;
for(int i=0; i<3; i++)
{
a = bufferedReader.readLine();
b = bufferedReader.readLine();
c = bufferedReader.readLine();
d = bufferedReader.readLine();
table.setValueAt(a, i, 0);
table.setValueAt(b, i, 1);
table.setValueAt(c, i, 2);
table.setValueAt(d, i, 3);
}
} catch (FileNotFoundException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
} finally {
//Close the reader
try {
if (bufferedReader != null) {
bufferedReader.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
And it is called in this way:
readFromFile("C:/data/datafile.txt", table1)
The problem is the following: the 1st time I open the program the *.txt file I'm going to read does not exist, so I thought I could use the function exists(). I have no idea about what to do, but I tried this:
if(("C:/data/datafile.txt").exists()) {
readFromFile("C:/data/datafile.txt", table1)
}
It is not working because NetBeans gives me a lot of errors. How could I fix this?
String has no method named exists() (and even if it did it would not do what you require), which will be the cause of the errors reported by the IDE.
Create an instance of File and invoke exists() on the File instance:
if (new File("C:/data/datafile.txt").exists())
{
}
Note: This answer use classes that aren't available on a version less than Java 7.
The method exists() for the object String doesn't exist. See the String documentation for more information. If you want to check if a file exist base on a path you should use Path with Files to verify the existence of the file.
Path file = Paths.get("C:/data/datafile.txt");
if(Files.exists(file)){
//your code here
}
Some tutorial about the Path class : Oracle tutorial
And a blog post about How to manipulate files in Java 7
Suggestion for your code:
I'll point to you the tutorial about try-with-resources as it could be useful to you. I also want to bring your attention on Files#readAllLines as it could help you reduce the code for the reading operation. Based on this method you could use a for-each loop to add all the lines of the file on your JTable.
you can use this code to check if the file exist
Using java.io.File
File f = new File(filePathString);
if(f.exists()) { /* do something */ }
You need to give it an actual File object. You're on the right track, but NetBeans (and java, for that matter) has no idea what '("C:/data/datafile.txt")' is.
What you probably wanted to do there was create a java.io.File object using that string as the argument, like so:
File file = new File ("C:/data/datafile.txt");
if (file.exists()) {
readFromFile("C:/data/datafile.txt", table1);
}
Also, you were missing a semicolon at the end of the readFromFile call. Im not sure if that is just a typo, but you'll want to check on that as well.
If you know you're only ever using this File object just to check existence, you could also do:
if (new File("C:/data/datafile.txt").exists()) {
readFromFile("C:/data/datafile.txt", table1);
}
If you want to ensure that you can read from the file, it might even be appropriate to use:
if(new File("C:/data/datafile.txt").canRead()){
...
}
as a condition, in order to verify that the file exists and you have sufficient permissions to read from the file.
Link to canRead() javadoc

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

Exporting to CSV/Excel in Java

I'm trying to export data into a CSV file through Java and I've got some code to do it but it doesn't seem to be outputting the CSV file. Could someone tell me what's wrong? What I would like to do is rather than saving the file somewhere, I would like it to be directly exported to the user.
EDIT: Just in case it's not clear, I don't want the file to be saved anywhere but would like it to be outputted automatically to the user i.e. they click export and get the "Run/Save results.csv" window and they open the file. Currently the file is getting saved so I know that the method seems to work, just in the opposite way that I want it to.
public static void writeToCSV(List<Map> objectList) {
String CSV_SEPARATOR = ",";
try {
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream("results.csv"), "UTF-8"));
for (Map objectDetails : objectList) {
StringBuffer oneLine = new StringBuffer();
Iterator it = objectDetails.values().iterator();
while (it.hasNext()) {
Object value = it.next();
if(value !=null){
oneLine.append(value.toString());
}
if (it.hasNext()) {
oneLine.append(CSV_SEPARATOR);
}
}
bw.write(oneLine.toString());
bw.newLine();
}
bw.flush();
bw.close();
} catch (UnsupportedEncodingException e) {
} catch (FileNotFoundException e) {
} catch (IOException e) {
}
}
I would recommend using a framework like opencsv for that. It also does escaping and quoting for you.
If you're not getting errors, check the directory where your code is. Without a specific path, your file is being saved there.
EDIT: Since the file is being saved and you want it to open automatically, use
Runtime.getRuntime().exec("results.csv");
(For Windows - opens the csv file in the default application for csv files)
Runtime.getRuntime().exec("open results.csv");
(For Mac - opens the csv file in the default application for csv files)
recommend HSSFWorkbook to easily read and write excel files.
http://poi.apache.org/apidocs/org/apache/poi/hssf/usermodel/HSSFWorkbook.html
To do that, the CSV reader need to read the memory of your program. This is a little complex thing to do. So, save the file in a temp folder instead. There is no problem to do this sort of thing.

Categories

Resources