Writing to Files : Printwriter Converting Forward Slash to Backslash - java

Why is Printwriter doing this?
File file = new File("/files/KA.txt");
writer = new PrintWriter(file);
writer.write("HELLO");
In the above code I keep getting an error that says :
java.io.FileNotFoundException: \files\KA.txt (The network path was not found)
Except this was not my specified path? How do I then specify a file to write - usually create a new file and write to this? It also throws errors if KA.txt is not present - I ideally want to create a new file and writer to it.
Thanks

I ideally want to create a new file and writer to it.
You can simply create a file ,
PrintWriter writer = new PrintWriter("name.txt", "UTF-8");
writer.println("text");
where UTF-8 is the file encoding. and write to the file , remember it overrides if the file exists with the same name

The problem is that the parent /files directory doesn't already exist, so you must create it beforehand, using File.mkdirs.
File file = new File("/files/KA.txt");
File parentFile = file.getParentFile();
parentFile.mkdirs();
PrintWriter writer = new PrintWriter(file);
writer.write("HELLO");
writer.close();

Related

Java: How to get the path of an empty resource folder [duplicate]

I am trying to write a .txt file in a resource folder but it doesn't write anything. I am able to read the same .txt file by doing:
Scanner scanner = null;
InputStream IS = MyClass.class.getResourceAsStream("/File/My FileH");
scanner = new Scanner(IS);
But when it comes to write, I have tried doing:
PrintWriter writer = new PrintWriter(
new File(this.getClass().getResource("/File/My FileH").getFile()));
writer.println("hello");
writer.close();
Any suggestions on how to write in that folder?
You can't write something in to a resource, assume that you packed your resource as a jar. Jar is only read only. You can't update that. Either you can extract the jar and edit the contents.
You can try Preferences as an alternative

PrintWriter not outputing to file

Whenever the next segment of code is run, I get the new csv file created, but I don't get anything written to it:
PrintWriter fout = null;
try {
// create file
fout= new PrintWriter("EEGLogger.csv");
String headerFile = "IED_COUNTER, IED_INTERPOLATED, IED_RAW_CQ, IED_AF3, IED_F7, IED_F3, IED_FC5, IED_T7, " +
"IED_P7, IED_O1, IED_O2, IED_P8, IED_T8, IED_FC6, IED_F4, IED_F8, IED_AF4, " +
"IED_GYROX, IED_GYROY,IED_TIMESTAMP";
// Writes the header to the file
fout.println(headerFile);
fout.println();
...
I do a fout.close() in a finally statement, but that still doesn't help get any output to the file. Any ideas here?
Either:
You are looking in the wrong place, i.e. not the current working directory, or
You don't have write access to the current working directory.
If you had used a FileWriter and not got an IOException, that would rule out (2).
I've seen about a million answers and comments here this week claiming that the current working directory equals the location of the JAR file, but it doesn't.
You could open a FileWriter
fout = new PrintWriter(new FileWriter("EEGLogger.csv"));
...
fout.flush();
fout.close()
I believe the PrintWriter is intended for formatting and character encoding. api docs states Prints formatted representations of objects to a text-output stream and as well Methods in this class never throw I/O exceptions.
Using the FileWriter as parameter would force you to handle any IOException that may happen so if the file is not created or not writable, you will immediately get this information.
Another situation can happen if the file is created and you are just looking for the file at incorrect location. I'd suggest to create a File object too, to see where the file really resides (what's your real working directory)
File f = new File("EEGLogger.csv");
fout = new PrintWriter(new FileWriter(f));
System.out.println(f.getAbsolutePath());

Creating Directories and Sub directories and getting files inside sub directories [duplicate]

I want to write a new file with the FileWriter. I use it like this:
FileWriter newJsp = new FileWriter("C:\\user\Desktop\dir1\dir2\filename.txt");
Now dir1 and dir2 currently don't exist. I want Java to create them automatically if they aren't already there. Actually Java should set up the whole file path if not already existing.
How can I achieve this?
Something like:
File file = new File("C:\\user\\Desktop\\dir1\\dir2\\filename.txt");
file.getParentFile().mkdirs();
FileWriter writer = new FileWriter(file);
Since Java 1.7 you can use Files.createFile:
Path pathToFile = Paths.get("/home/joe/foo/bar/myFile.txt");
Files.createDirectories(pathToFile.getParent());
Files.createFile(pathToFile);
Use File.mkdirs():
File dir = new File("C:\\user\\Desktop\\dir1\\dir2");
dir.mkdirs();
File file = new File(dir, "filename.txt");
FileWriter newJsp = new FileWriter(file);
Use File.mkdirs().
Use FileUtils to handle all these headaches.
Edit: For example, use below code to write to a file, this method will 'checking and creating the parent directory if it does not exist'.
openOutputStream(File file [, boolean append])

Create File at user defined path

I am creating a file in java using
BufferedWriter out = new BufferedWriter(new FileWriter(FileName));
StringBuffer sb=new StringBuffer();
sb.append("\n");
sb.append("work");
out.write(sb.toString());
out.close();
But this file is getting created inside the bin folder of my server.I would like to create this file inside a user-defined folder.
How can it be achieved.
I would like to create this file inside a user-defined folder.
The simplest approach is to specify a fully qualified path name. You could select that as a File and build a new File relative to it:
File directory = new File("/home/jon/somewhere");
File fullPath = new File(directory, fileName);
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(
(new FileOutputStream(fullPath), charSet));
try {
writer.write("\n");
writer.write("work");
} finally {
writer.close();
}
Note:
I would suggest using a FileOutputStream wrapped in an OutputStreamWriter instead of using FileWriter, as you can't specify an encoding with FileWriter
Use a try/finally block (or try-with-resources in Java 7) so that you always close the writer even if there's an exception.
To create a file in a specific directory, you need to specify it in the file name.
Otherwise it will use the current working directory which is likely to be where the program was started from.
BTW: Unless you are using Java 1.4 or older, you can use StringBuilder instead of StringBuffer, although in this case PrintWriter would be even better.

Create whole path automatically when writing to a new file

I want to write a new file with the FileWriter. I use it like this:
FileWriter newJsp = new FileWriter("C:\\user\Desktop\dir1\dir2\filename.txt");
Now dir1 and dir2 currently don't exist. I want Java to create them automatically if they aren't already there. Actually Java should set up the whole file path if not already existing.
How can I achieve this?
Something like:
File file = new File("C:\\user\\Desktop\\dir1\\dir2\\filename.txt");
file.getParentFile().mkdirs();
FileWriter writer = new FileWriter(file);
Since Java 1.7 you can use Files.createFile:
Path pathToFile = Paths.get("/home/joe/foo/bar/myFile.txt");
Files.createDirectories(pathToFile.getParent());
Files.createFile(pathToFile);
Use File.mkdirs():
File dir = new File("C:\\user\\Desktop\\dir1\\dir2");
dir.mkdirs();
File file = new File(dir, "filename.txt");
FileWriter newJsp = new FileWriter(file);
Use File.mkdirs().
Use FileUtils to handle all these headaches.
Edit: For example, use below code to write to a file, this method will 'checking and creating the parent directory if it does not exist'.
openOutputStream(File file [, boolean append])

Categories

Resources