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

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

Related

Can We download Zip for multiple txt files without downloading the txt fileS in java?

Can we write into multiple txt files and download them directly as zip (Without downloading txt files )
When we write in file it is done in physical file. But when we want to create zip of that reference it will consider the object file .
Is there any way to store data in object file then download it as zip .??
File file = new File("/Users/VYadav/Desktop/lex/sitemap.txt"); // creates local object
String zipFileName = "/Users/VYadav/Desktop/lex/zipname.zip";
FileOutputStream fos = new FileOutputStream(zipFileName);
ZipOutputStream zos = new ZipOutputStream(fos);
PrintWriter pw=new PrintWriter(file); // creates a physical file on disk
pw.write("Hii"); // writes in physical file
pw.flush();
ZipEntry ze = new ZipEntry(file.getName()); // Reads from local object (here data is not present)
zos.putNextEntry(ze);
The out put of this code will be one txt file having "Hii" as data and a zip file containing a blank txt file .
because file is put into zip entry from objet.
Is there any way to update our data in the object then download into zip folder ??
You can write Zip file with all the "zipped" files created on-the-fly.
Since you're talking about "downloading", I'll assume that you're in a webapp, and want to generate the zip file directly back to the client, so you need to create the ZipOutputStream against the response stream, not a file. E.g. in a Servlet webapp, you'd do it like this:
response.setContentType("application/zip");
ZipOutputStream zos = new ZipOutputStream(response.getOutputStream());
PrintWriter out = new PrintWriter(zos);
zos.putNextEntry(new ZipEntry("Foo.txt"));
// write content of Foo.txt here, e.g.
out.println("Hello Foo");
out.flush();
zos.putNextEntry(new ZipEntry("Bar.txt"));
// write content of Bar.txt here, e.g.
out.println("Hello Bar");
out.flush();
zos.putNextEntry(new ZipEntry("Baz.png"));
// write content of Baz.png here, e.g. copy bytes from file on classpath
try (InputStream in = this.getClass().getResourceAsStream("logo.png")) {
byte[] buf = new byte[8192];
for (int len; (len = in.read(buf)) > 0; )
zos.write(buf, 0, len);
}
// Complete the zip file.
zos.finish(); // or zos.close()

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

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

Text File writing in Java

I am writing String content to text file in Java code but after writing saving file onto disk, I am getting Incorrect encoding exception, Please suggest me correct Java Code?
String content =fileContent;//fileContent.toString();
System.out.println("File Contt===>"+content);
File fileWrite = new File("/homeDesktop/NormalFile/"+filename);
// if file doesnt exists, then create it
if (!fileWrite.exists()) {
fileWrite.createNewFile();
}
FileWriter fw = new FileWriter(fileWrite.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
bw.write(fileContent);
bw.close();
IOUtils.toString(String) Converts your coding.
String not encoded in UTF-8
NOTE:
You dont need this:
// if file doesnt exists, then create it
if (!fileWrite.exists()) {
fileWrite.createNewFile();
}
File create automatically a new file, if there isn't one.

Write String to multiple txt files

The following code writes a string to a specific file.
String content = "Text To be written on a File";
File file = new File("c:/file.txt");
FileOutputStream foutput = new FileOutputStream(file);
if (!file.exists()) {
file.createNewFile();
}
byte[] c = content.getBytes();
foutput.write(c);
foutput.flush();
foutput.close();
I want to use this code in a Jbutton so every time the user clicks it, it writes the string to a NEW text file NOT OVERWRITE the existed one. I tried to do but I couldn't get the result.
Thank you in advance.
There's a couple of different ways you can get this result, it really depends on the application. The two easiest ways to do this would to be either:
Append the current timestamp to the file name
Use the File API to create a "temp file" in the directory, which is guarenteed to have a unique name
Option 1:
String baseDir = "c:/";
File newFile = new File(baseDir, "file_" + System.currentTimeMillis() + ".txt");
// do file IO logic here...
Option 2:
String baseDir = "c:/";
File newFile = File.createTempFile("file", ".txt", new File(baseDir));
// do file IO logic here...
If you want to write it to a new file, you have to create a new file. The name of the text file is always file.txt in your case.
Try this:
private int filecounter = 0; // this is the member of your class. Outside the function.
//inside your function
File file = new File("c:/file" + Integer.(filecounter).toString() + ".txt");
// you do something here.
filecounter++;
This way, your files will be stored as file0.txt, file1.txt etc.

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