I am trying to understand PrintWriter for a small program I'm making, and I cant seem to get java to make the file and then write on it. When I execute the program below it gives me a Filenotfoundexeption error on line 9. It also fails to make the file in the directory that I specified. I am new to this so please try and keep the answers simple. I am using Eclipse.
import java.io.PrintWriter;
import java.io.File;
public class Testing {
public static void main(String[] args) {
File file = new File ("C:/Users/Me/Desktop/directory/file.txt");
PrintWriter printWriter = new PrintWriter ("file.txt");
printWriter.println ("hello");
printWriter.close ();
}
}
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);
import java.io.PrintWriter;
import java.io.File;
public class Testing {
public static void main(String[] args) throws IOException {
File file = new File ("C:/Users/Me/Desktop/directory/file.txt");
PrintWriter printWriter = new PrintWriter ("file.txt");
printWriter.println ("hello");
printWriter.close ();
}
}
throw an exception for the file.
Pass the File object to the constructor PrintWriter(File file):
PrintWriter printWriter = new PrintWriter(file);
import java.io.File;
import java.io.PrintWriter;
public class Testing
{
public static void main(String[] args)
{
File file = new File("C:/Users/Me/Desktop/directory/file.txt");
PrintWriter printWriter = null;
try
{
printWriter = new PrintWriter(file);
printWriter.println("hello");
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
finally
{
if ( printWriter != null )
{
printWriter.close();
}
}
}
}
You should have a clear idea of exceptions in java.
In java there are checked exceptions and unchecked exceptions.
Checked exceptions are checked (not thrown,just checked) by the compiler at Compile time for the smooth execution of the program at run time.
NOTE: And in our program if their is a chance that a checked exception will rise, then we should handle that checked exception either by try catch or by throws key word.Otherwise we will get a compile time Error:
CE:Unexpected Exception java.io.FileNotFoundException;must be caught or declared to be thrown.
How to resolve:
1.Put your code in try catch block:
2.use throws keyword as shown by other guys above.
Advice:Read more about Exceptions.(I personally love this topic)
Java doesn't normally accept "/" to use in defining a file directory, so try this:
File file = new File ("C:\\Users\\user\\workspace\\FileTester\\myFile.txt");
If the file doesn't exist do:
try {
file.createNewFile();
}
catch (IOException e) {
e.printStackTrace();
}
Well I think firstly keep whole main into try catch(or you can use as public static void main(String arg[]) throws IOException ) and then also use full path of file in which you are writing as
PrintWriter printWriter = new PrintWriter ("C:/Users/Me/Desktop/directory/file.txt");
all those directies like users,Me,Desktop,directory should be user made. java wont make directories own its own.
it should be as
import java.io.*;
public class PrintWriterClass {
public static void main(String arg[]) throws IOException{
PrintWriter pw = new PrintWriter("C:/Users/Me/Desktop/directory/file.txt");
pw.println("hiiiiiii");
pw.close();
}
}
import java.io.*;
public class test{
public static void main(Strings []args){
PrintWriter pw = new PrintWriter(new file("C:/Users/Me/Desktop/directory/file.txt"));
pw.println("hello");
pw.close
}
}
The PrintWriter class can actually create the file for you.
This example works in JDK 1.7+.
// This will create the file.txt in your working directory.
PrintWriter printWriter = null;
try {
printWriter = new PrintWriter("file.txt", "UTF-8");
// The second parameter determines the encoding. It can be
// any valid encoding, but I used UTF-8 as an example.
} catch (FileNotFoundException | UnsupportedEncodingException error) {
error.printStackTrace();
}
printWriter.println("Write whatever you like in your file.txt");
// Make sure to close the printWriter object otherwise nothing
// will be written to your file.txt and it will be blank.
printWriter.close();
For a list of valid encodings, see the documentation.
Alternatively, you can just pass the file path to the PrintWriter class without declaring the encoding.
Double click the file.txt, then save it, command + s, that worked in my case. Also, make sure the file.txt is saved in the project folder.
If that does not work.
PrintWriter pw = new PrintWriter(new File("file.txt"));
pw.println("hello world"); // to test if it works.
If you want to use PrintWrite then try this code
public class PrintWriter {
public static void main(String[] args) throws IOException {
java.io.PrintWriter pw=new java.io.PrintWriter("file.txt");
pw.println("hello world");
pw.flush();
pw.close();
}
}
Related
I would like to create a new file using filewriter class and use the exact path in file class (don't want to copy/paste the manually, any changes in file writer path, we would like to reflect the instances) to get absolute path of the particular file. Can anyone suggest me how?
First I would create a filewriter and later want to use File to display it's attributes such that any chnages in Fiewriter URL would be displayed.
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
public class files_read {
public static void main(String[] args) {
// TODO Auto-generated method stub
try {
FileWriter FW=new FileWriter("C:/Users/91870/Downloads/Boss.txt");
FW.write("yoyo");
FW.close();
File f=new File(FW);
}
catch(IOException ie)
{
System.out.println("An error occurred.");
ie.printStackTrace();
}
}
}
You should do it the other way around. First create the File instance and then the FileWriter with that File instance.
File f = new File("C:/Users/91870/Downloads/Boss.txt");
FileWriter fw = new FileWriter(f);
...
Let me explain the situation. In Windows OS.
My java program writes the logfile.
Usually It's OK, but when I copying and pasting the logfile(ctrl + c and v),
java throws exception java.io.IOException: java.io.FileNotFoundException: C:\log.txt (The process cannot access the file because it is being used by another process)
After I research the problem, I found this exception throws by pasting the file. Not copying.
Please tell me why this exception occur.
Reproduce code is below(encode "Windows-31J" is japanese, there is no
particular meaning). Excecute this program and copy and paste "C:\log.txt".
package test;
import java.io.BufferedWriter;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.stream.IntStream;
public class FileNotFound {
public static void main(String[] args) {
IntStream.range(0, 100000).parallel().forEach(
i -> {
try {
fileWrite("C:\\log.txt", String.valueOf(i));
} catch (IOException e) {
e.printStackTrace();
}
}
);
}
public static void fileWrite(String filePath, String str) throws IOException {
try (FileOutputStream fw = new FileOutputStream(filePath, true);
OutputStreamWriter ow = new OutputStreamWriter(fw, "Windows-31J");
BufferedWriter bw = new BufferedWriter(ow);
PrintWriter out = new PrintWriter(bw)) {
out.println(str);
} catch (IOException e) {
throw new IOException(e);
}
}
}
It occurs because another process, i.e. your Explorer window, is using the file, via the 'copy' action, which Windows does not allow. Solution: don't.
I have this code below. Basically I'm getting an input from a given url. This website shows a sentence. Each time I reload the website it gets a new sentence and so on. So, I managed to get that working. Now I'm trying to write the sentence in a textfile. But something is wrong. It only writes the first line and nothing else. What's wrong with my code?
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
public class ReadIp {
public static void main(String[] args) throws MalformedURLException, IOException,
InterruptedException {
ReadIp readIP = new ReadIp();
while (true) {
readIP.getIP();
Thread.sleep(2000);
}
}
BufferedReader buff;
InputStreamReader inStream;
String line;
URL url;
URLConnection urlConn;
FileWriter fileWriter ;
BufferedWriter bufferedWriter;
public ReadIp() throws IOException {
fileWriter = new FileWriter("myfile.txt", true);
bufferedWriter = new BufferedWriter(fileWriter);
}
public void getIP() throws MalformedURLException, IOException {
this.url = new URL("http://test.myrywebsite.co.uk");
this.urlConn = this.url.openConnection();
this.inStream = new InputStreamReader(this.urlConn.getInputStream());
this.buff = new BufferedReader(this.inStream);
try {
while ((this.line = this.buff.readLine()) != null)
{
System.out.println(this.line);
try {
this.bufferedWriter.write(this.line);
this.bufferedWriter.write("\n");
this.bufferedWriter.flush();
} catch (IOException e)
{
}
}
if (this.bufferedWriter != null)
{
this.bufferedWriter.close();
}
this.inStream.close();
}
catch (Exception ex)
{
}
}
}
Any help would be greatly appreciated.
Thank you.
Move the statement
writer.close();
out of the inner try catch block so that you're not closing the OutputStream after writing the first entry to the file. The same applys to the InputStream
inStream.close();
The BufferedWriter is being opened in the constructor and is being closed in getIp. The constructor is called only once, but getIp is called every 2 seconds to read a sentence. So the BufferedWriter is being closed after the first line (and not opened again). The second call of getIp tries to write the second sentence but the BufferedWriter is closed. This should throw an Exception which is being ignored since the catch block is empty.
Never leave a catch block empty - as fgb wrote above!
First of all, at least add a printStackTrace() to each empty catch block, e.g.:
catch (Exception ex) {
ex.printStackTrace();
}
so you can see if an Exception is being thrown...
I would suggest to open the BufferedWriter in the method getIp instead of the constructor; or, if it should stay open all the time, close the BufferedWriter in an additional method, called after the loop in main terminates
I'm write some text a file then delete it, but the deletion is failed.
The code is very simple:
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
public class TestFile {
public static void main(String[] args) throws IOException {
File file = new File("c:\\abc.txt");
writeFile(file, "hello");
// delete the file
boolean deleted = file.delete();
System.out.println("Deleted? " + deleted);
}
public static void writeFile(File file, String content) throws IOException {
OutputStream out = null;
try {
out = new FileOutputStream(file);
out.write(content.getBytes("UTF-8"));
} catch (IOException e) {
try {
out.close();
} catch (IOException e1) {
// ignored
}
}
}
}
The output is:
Deleted? false
And there is a file abc.txt contains hello still there under c:.
Then I use FileUtils.writeStringToFile(...) from commons-io.jar instead, the file will be deleted.
But I don't know where is wrong with my code, please help me to find it out.
You are only closing the file if you get an IOException.
Change it to a finally block and you will be able to close and delete the file.
public static void writeFile(File file, String content) throws IOException {
OutputStream out = new FileOutputStream(file);
try {
out.write(content.getBytes("UTF-8"));
} finally {
try {
out.close();
} catch (IOException ignored) {
}
}
}
You need to close your OutputStream when you finished writing the file.
try {
out = new FileOutputStream(file);
out.write(content.getBytes("UTF-8"));
out.close();
} catch (IOException e) {
try {
out.close();
} catch (IOException e1) {
// ignored
}
}
In your main method,
public static void main(String[] args) throws IOException {
File file = new File("c:\\abc.txt");
writeFile(file, "hello");
// delete the file
boolean deleted = file.delete();
System.out.println("Deleted? " + deleted);
}
You open the file, write to it and then do not close it. Java keeps the file open for you, so if you wanted to add more information to it, you could. However, to be able to delete the file, you need to make sure no other reference is open to it. You can do this by using file.close() to close the file handle Java reserves for you.
It's best practice to always close a stream when you are done with it, especially if you added data to it. Otherwise, you might run into situations where you are keepings files open by accident, or, in extreme cases, lose data you thought was saved already.
Have a look at what FileUtils.writeStringToFile() does that you haven't.
public static void writeStringToFile(File file, String data, String encoding) throws IOException {
OutputStream out = new java.io.FileOutputStream(file);
try {
out.write(data.getBytes(encoding));
} finally {
IOUtils.closeQuietly(out);
}
}
You will note that the out stream is always closed, wheras in your example it only gets closed in your catch block if the write() throws an exception.
On Windows, files that are open by any program cannot be deleted.
You just delete your file if an exception occurs. You need to do that every time, after you opened the file.
You may want to put close into a finally block.
If you're using Java 7 I consider using a try-with-ressources block, which takes care of closing files for you.
try (BufferedReader br = new BufferedReader(new FileReader(path)))
{
return br.readLine();
}
I need to capture the exception in a text file in Java. For example:
try {
File f = new File("");
}
catch(FileNotFoundException f) {
f.printStackTrace(); // instead of printing into console it should write into a text file
writePrintStackTrace(f.getMessage()); // this is my own method where I store f.getMessage() into a text file.
}
Using getMessage() works, but it only shows the error message. I want all the information in the printStackTrace() including line numbers.
It accepts a PrintStream as a parameter; see the documentation.
File file = new File("test.log");
PrintStream ps = new PrintStream(file);
try {
// something
} catch (Exception ex) {
ex.printStackTrace(ps);
}
ps.close();
See also Difference between printStackTrace() and toString()
Try to expand on this simple example:
catch (Exception e) {
PrintWriter pw = new PrintWriter(new File("file.txt"));
e.printStackTrace(pw);
pw.close();
}
As you can see, printStackTrace() has overloads.
Do set the err/out stream using System class.
PrintStream newErr;
PrintStream newOut;
// assign FileOutputStream to these two objects. And then it will be written on your files.
System.setErr(newErr);
System.setOut(newOut);
There is an API in Throwable interface getStackTrace() which is used internally for printing in console by printStackTrace()
http://docs.oracle.com/javase/1.4.2/docs/api/java/lang/Throwable.html#getStackTrace()
Try this API to get StackTraceElement and print those elements sequentially.
Hope below example helps you-
package com.kodehelp.javaio;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintStream;
public class PrintStackTraceToFile {
public static void main(String[] args) {
PrintStream ps= null;
try {
ps = new PrintStream(new File("/sample.log"));
throw new FileNotFoundException("Sample Exception");
} catch (FileNotFoundException e) {
e.printStackTrace(ps);
}
}
}
For more detail, refer to this link here