How to Use Printwriter and File Classes in Java

How to use PrintWriter and File classes in Java?

If the directory doesn't exist you need to create it. Java won't create it by itself since the File class is just a link to an entity that can also not exist at all.

As you stated the error is that the file cannot be created. If you read the documentation of PrintWriter constructor you can see

FileNotFoundException - If the given string does not denote an existing, writable regular file and a new regular file of that name cannot be created, or if some other error occurs while opening or creating the file

You should try creating a path for the folder it contains before:

File file = new File("C:/Users/Me/Desktop/directory/file.txt");
file.getParentFile().mkdirs();

PrintWriter printWriter = new PrintWriter(file);

how to use the same printwriter in multiple classes (java)

Constructor you are using to create a PrintWriter uses new instance of FileOutputStream internally.

The FileOutputStream has two general write models:

  • Overwrite (the default)
  • Append

Since you did not specify what mode to use, your writer will use the default. To tell it which mode you want, you will need to create FileOutputStream with correct mode. For example, like this:

try(PrintWriter out = new PrintWriter(new FileOutputStream("outputfile.txt", true))) {
// note the boolean parameter in FileOS constructor above. Its "true" value means "Append"
out.println(text);
} catch (FileNotFoundException e) {
e.printStackTrace();
}

There is something to be said about each class creating its own PrintWriter as well:

  • It duplicates the logic
  • It (possibly unnecessarily) ties whatever your class does with operation of output specifically into a file (what if you want to write over http instead?)
  • Operation of opening a file is usually not cheap, so you lose on performance there

I suggest that instead of each class creating its own output facility, it instead should receive one from outside:

class MyClass {
public void outputTo(PrintWriter w) {
String text = ...
w.println(text);
}
}

and you use it like this:

try (FileOutputStream fos = new FileOutputStream("filename", append);
PrintWriter w = new PrintWriter(fos)) {
new MyClass().outputTo(w); // first instance
new MyClass().outputTo(w); // second instance
//... etc.
}

Java IO: Using scanner and printWriter to copy the contents of a text file and put them in another text file

You have missed out flush() and close() for the PrintWriter object which you need to add

and then use the line separator using System.getProperty("line.separator") while writing each line into second file.

You can refer the below code:

PrintWriter printer = null;
Scanner sc = null;
try
{
String lineSeparator = System.getProperty("line.separator");

sc = new Scanner(new File(Input_filename));
FileWriter fw = new FileWriter(Output_filename);
printer = new PrintWriter(fw);

while(sc.hasNextLine())
{
String s = sc.nextLine()+lineSeparator; //Add line separator
printer.write(s);
}
}
catch(IOException ioe)
{
System.out.println(ioe);
} finally {
if(sc != null) {
sc.close();
}
if(printer != null) {
printer.flush();
printer.close();
}
}

Also, ensure that you are always closing resources in the finally block (which you have missed out for Scanner object in your code).

Reading from a text file and attempting to use printWriter to write to another results in a blank file

There is semicolon right after you while loop

while(scan.hasNextLine());
// ^

which makes it infinite loop because it represents empty instruction, just like

while(scan.hasNextLine()){}

so you are never actually entering

{
String stringRead = scan.nextLine();
pw.println(lineNumber + ": " + stringRead);
lineNumber++;
}

block, and code after it which means you are not writing anything to your result file and you don't even close it. All you have if empty file created with

FileOutputStream fos = new FileOutputStream("C:\\Users\\Reid\\Desktop\\rulicny.txt");

So remove this semicolon.


BTW you can easily spot this kind of mistakes if you will let your IDE format code for you. Eclipse formatted your example for me as

while (scan.hasNextLine())
;
{
String stringRead = scan.nextLine();
pw.println(lineNumber + ": " + stringRead);
lineNumber++;
}

which as you see shows it quite good that your loop actually executes empty statement instead of code block.



Related Topics



Leave a reply



Submit