Writing to file in netBeans IDE in java - java

public class FileWriterClass {
/**
* #param args the command line arguments
* #throws java.io.IOException
*/
public static void main(String[] args) throws IOException {
// TODO code application logic here
FileWriter fr = new FileWriter("hello.txt");
BufferedWriter br = new BufferedWriter(fr);
br.write("helllllllllllllllll");
}
}
its not writing into file.please help me out

You should always call the close() once you finish writing the data.
public class FileWriterClass {
/**
* #param args the command line arguments
* #throws java.io.IOException
*/
public static void main(String[] args) throws IOException {
// TODO code application logic here
FileWriter fr = new FileWriter("hello.txt");
BufferedWriter br = new BufferedWriter(fr);
br.write("helllllllllllllllll");
br.close();
fr.close();
}
}

You need to make sure the writers are closed, which will flush the buffer to disk. You need to do this because Java makes no guarentees that the objects will be finalised and closed automatically.
To make life easier for yourself, you can make use of the The try-with-resources Statement, which will close the writers automatically, even if there is an exception during the write process
public class FileWriterClass {
public static void main(String[] args) throws IOException {
try (FileWriter fr = new FileWriter("hello.txt");
BufferedWriter br = new BufferedWriter(fr)) {
br.write("helllllllllllllllll");
}
}
}

Since you are not Closing the Resources That's why it write Continuous.
and must have to put risky code inside Try catch block. must have to use close and flush the File Operation
Updated Code : -
public class FileWriterClass {
public static void main(String[] args){
try{
FileWriter fr = new FileWriter("hello.txt");
BufferedWriter br = new BufferedWriter(fr);
br.write("helllllllllllllllll");
br.close();
}catch(IOException i){
i.printStackTrace();
}}}

Try to close() the BufferedWriter and FileWriter like this:
br.write("helllllllllllllllll");
br.close();
fr.close();

You could use the utility methods of java.lang.nio.file.Files. Which removes the need to write to much boilerplate code.
public class FileWriterClass {
public static void main(String[] args) throws IOException {
// path to the file to write, in this case the file
// will be created in the current directory
Path path = Paths.get("hello.txt");
// the character set of the file
Charset fileCharset = StandardCharsets.UTF_8;
// the needed code to write to the file
try (BufferedWriter bw = Files.newBufferedWriter(path, fileCharset)) {
bw.write("hello NIO 2");
}
}
}

Related

Do I need to keep variables for all writers/readers to close them all manually?

Consider this example:
public class FileAppender implements AutoCloseable {
private final FileWriter fileWriter;
private final BufferedWriter bufferedWriter;
public FileAppender(String fileName) throws IOException {
fileWriter = new FileWriter(fileName, true)
bufferedWriter = new BufferedWriter(fileWriter);
}
public void appendLine(String line) throws IOException {
bufferedWriter.write(line + "\n");
}
#Override
public void close() throws Exception {
bufferedWriter.close();
fileWriter.close();
}
}
Here we keep an unused FileWriter as a member of the class, just so we can manually close it later. There are many tutorials in the web which show examples like this where multiple streams are closed manually.
We could instead implement the same class more concisely:
public class FileAppender implements AutoCloseable {
private final BufferedWriter writer;
public FileAppender(String fileName) throws IOException {
writer = new BufferedWriter(new FileWriter(fileName, true));
}
public void appendLine(String line) throws IOException {
writer.write(line + "\n");
}
#Override
public void close() throws Exception {
writer.close();
}
}
Same applies to the usage of FileReader and BufferedReader.
Would there be any difference between the above two implementations?
With BufferedWriter, specifically, you can just use close on the BufferedWriter and it will call close on the underlying FileWriter.
But, as far as I'm aware, that's not documented, and not required of Writer implementations that wrap other Writers (and similarly, streams). I'm paranoid, and tend to close things explicitly (in reverse order of opening them).
You can see the close operation in the BufferedWriter source (this example is from JDK 11.0.1), though you have to look fairly closely:
public void close() throws IOException {
synchronized (lock) {
if (out == null) {
return;
}
try (Writer w = out) {
flushBuffer();
} finally {
out = null;
cb = null;
}
}
}
Note the use of try-with-resources to auto-close out (via w).

Bad practice in JDK's try-with-resources example? [duplicate]

This question already has answers here:
Correct idiom for managing multiple chained resources in try-with-resources block?
(8 answers)
Closed 5 years ago.
I found this example in the try-with-resources documentation for Java:
static String readFirstLineFromFile(String path) throws IOException {
try (BufferedReader br = new BufferedReader(new FileReader(path))) {
return br.readLine();
}
}
If the constructor for BufferedReader throws an exception, then the resources held by the FileReader won't be released. So isn't this a bad practice to write it like that instead of:
static String readFirstLineFromFile(String path) throws IOException {
try (FileReader fr = new FileReader(path);
BufferedReader br = new BufferedReader(fr)) {
return br.readLine();
}
}
Indeed, just gave it a quick try:
public class MyFileReader extends FileReader {
public MyFileReader(String fileName) throws FileNotFoundException {
super(fileName);
}
#Override
public void close() throws IOException {
System.out.println("Closing MyFileReader");
super.close();
}
}
public class MyBufferedReader extends BufferedReader {
public MyBufferedReader(Reader in) {
super(in);
throw new RuntimeException();
}
#Override
public void close() throws IOException {
System.out.println("Closing MyBufferedReader");
super.close();
}
}
public String test(String path) throws IOException {
try (BufferedReader br = new MyBufferedReader(new MyFileReader(path))) {
return br.readLine();
}
}
None of MyFileReader nor MyBufferedReader is closed... Good catch!
While with:
public String test(String path) throws IOException {
try (FileReader fr = new MyFileReader(path); BufferedReader br = new MyBufferedReader(fr)) {
return br.readLine();
}
}
MyFileReader is closed.
BufferedReader constructor can indeed throw exceptions, see BufferedReader(Reader in, int sz) constructor (although not when coming from BufferedReader(Reader in) constructor, but the doc you linked should still alert on this possible issue IMHO).
Looks like you won the right to raise an issue :)
Unfortunately, you are right.
The below example shows this behaviour - instance of Internal is never closed.
public class Test {
public static void main(String[] args) {
try (External external = new External(new Internal())) {
}
}
}
class External implements Closeable {
private Internal internal;
public External(Internal internal) {
this.internal = internal;
throw new RuntimeException("boom");
}
#Override
public void close() {
System.out.println("External.close()");
internal.close();
}
}
class Internal implements Closeable {
#Override
public void close() {
System.out.println("Internal.close()");
}
}

Read file with BufferReader when multiple thread writing to the file

All, I am trying to read a file which will be written by multiple threads, I am going to use BufferedReader to read that file in a thread.
The code looks like below.
FileReader reader = new FileReader(file);
BufferedReader br = new BufferedReader(reader);
String detail;
while ((detail =br.readLine()) != null)
{
...
}
Currently It seems works fine. But I have some questions about it.
If the question sound silly. please don't laugh at me . thanks.
Is it possible that the loop never been broken ? because the other threads are writing into the file.So maybe the readLine() may never return null?
Updated
Let's say there are 3 threads(T1,T2,T3).
T1 and T2 are writer.
T3 is reader.
The code runs in below sequence.
1.The current file lines number is 100.
2.T1 write a line to file.(file lines increase to 101)
3.T3 reads the last line of file(101). next read will get null.
4.T2 append a line to file.(file lines increase to 102)
5.T3 read again....(Does it return null or not? because T2 just added a new line into file before T3 read again.)
Please help to review it .thanks in advance.
Yes, it is possible that the loop will never end (at least until you run out of memory). Here's some code to prove it:
public class test {
public static void main(String[] args) {
// start thread to write to file
new Thread(new Runnable() {
#Override
public void run() {
FileWriter writer;
try {
int i = 1;
writer = new FileWriter("D:\\text.txt");
writer.append("line"+ i++ + "\n");
writer.flush();
while (true)
{
writer.append("line"+ i++ + "\n");
writer.flush();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
try {
Thread.sleep(500);
} catch (InterruptedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
// start thread to read file
new Thread(new Runnable() {
#Override
public void run() {
try {
FileReader reader = new FileReader("D:\\text.txt");
BufferedReader br = new BufferedReader(reader);
String detail;
while ((detail =br.readLine()) != null)
{
System.out.println(detail);
}
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
}
}
I did some experiment for it .
One eclipse run a program as writer .
public class Main {
private static Logger log = Logger.getLogger(Main.class);
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
PropertyConfigurator.configure("log4j.properties");
log.warn("Test test test ");
}
}
Another eclipse run the program as reader.
public class Main {
/**
* #param args
* #throws IOException
*/
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
StringBuffer intiLine = new StringBuffer("");
FileReader reader = new FileReader("D:\\logs\\notify-subscription.log");
BufferedReader br = new BufferedReader(reader);
String detail;
while ((detail =br.readLine()) != null)//debug and set breakpoint here
{
System.out.println(detail);
}
}
}
before I began to test them. The original log file content is empty.
I ran the reader program at first. the result of br.readLine() supposed to be null. But I set break point at the code line while ((detail =br.readLine()) != null) run, before it run , I ran the writer program. So the file contains test test test. and br.readLine() will not be null.
You are absolutely Correct .There will be a chance for Deadlock also if you keep creating threads for writing content to the file.Because if threads are keep on writing to the file there wont be any chance of exiting from loop it goes to infinite state

Unreported exception java.io.FileNotFoundException;?

I want to open a file and scan it to print its tokens but I get the error: unreported exception java.io.FileNotFoundException; must be caught or declared to be thrown
Scanner stdin = new Scanner (file1); The file is in the same folder with the proper name.
import java.util.Scanner;
import java.io.File;
public class myzips {
public static void main(String[] args) {
File file1 = new File ("zips.txt");
Scanner stdin = new Scanner (file1);
String str = stdin.next();
System.out.println(str);
}
}
The constructor for Scanner you are using throws a FileNotFoundException which you must catch at compile time.
public static void main(String[] args) {
File file1 = new File ("zips.txt");
try (Scanner stdin = new Scanner (file1);){
String str = stdin.next();
System.out.println(str);
} catch (FileNotFoundException e) {
/* handle */
}
}
The above notation, where you declare and instantiate the Scanner inside the try within parentheses is only valid notation in Java 7. What this does is wrap your Scanner object with a close() call when you leave the try-catch block. You can read more about it here.
The file is but it may not be. You either need to declare that your method may throw a FileNotFoundException, like this:
public static void main(String[] args) throws FileNotFoundException { ... }
or you need to add a try -- catch block, like this:
Scanner scanner = null;
try {
scanner = new Scanner(file1);
catch (FileNotFoundException e) {
// handle it here
} finally {
if (scanner != null) scanner.close();
}

Using ordinary stream writers/readers with piped streams

Consider the following test code.
I am trying to find out if I can use piped streams like "normal" I/O streams, together with the commonly used Reader and Writer implementations (specifically, another part of the code base I am working on demands that I use OutputStreamWriter).
The problem here is that nothing appears to show up on the read end. The program at least appears to correctly write the message to the write-end of the pipe, but when trying to read from the other end I block indefinetly, or if I (as in this case) check for available bytes, the call returns 0.
What am I doing wrong?
public class PipeTest {
private InputStream input;
private OutputStream output;
public PipeTest() throws IOException {
input = new PipedInputStream();
output = new PipedOutputStream((PipedInputStream)input);
}
public void start() {
Stuff1 stuff1 = new Stuff1(input);
Stuff2 stuff2 = new Stuff2(output);
Thread thread = new Thread(stuff1);
thread.start();
Thread thread2 = new Thread(stuff2);
thread2.start();
}
public static void main(String[] args) throws IOException {
new PipeTest().start();
}
private static class Stuff1 implements Runnable {
InputStream inputStream;
public Stuff1(InputStream inputStream) {
this.inputStream = inputStream;
}
#Override
public void run() {
String message;
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
try {
//message = reader.readLine();
System.out.println("Got message!");
System.out.println(inputStream.available());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
private static class Stuff2 implements Runnable {
OutputStream outputStream;
public Stuff2(OutputStream outputStream) {
this.outputStream = outputStream;
}
#Override
public void run() {
String message = "Hej!!\n";
OutputStreamWriter writer = new OutputStreamWriter(outputStream);
try {
writer.write(message);
System.out.println("Wrote message!");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
As you are never reading from the read end, it is impossible to see how you could possibly arrive at that conclusion, and any such conclusion is therefore baseless and invalid.
All you are doing is printing available() at an arbitrary point in time, which isn't sufficient to prove that nothing ever shows up at the read end.

Categories

Resources