What is the recommended way close IO resources declared as instance variables - java

In some of the Java classes I see the IO resources declared as instance varibles and are being used in multiple methods.How can I close them?Few Suggested finalize() and they also say that it is not recommended. May I know if there is any better approach for this.?
Ex:
public class test{
private PrintWriter writer=null;
public test(){
createWriter();
}
public void log(){
writer.write("test");
writer.flush();
}
public void createWriter(){
writer=new PrintWriter(new BufferedWriter(new FileWriter("file")));
}
}

Implements AutoCloseable in your class and override close() method and close all your IO related resources in this close() method.
Now if you are using Java 7 you can create a reference to your class using try with resource and JVM will automatically call close method of your class.
As you can see in the code of FilterReader class,
public abstract class FilterReader extends Reader {
protected Reader in;
//......Other code, and then
public void close() throws IOException {
in.close();
}
}
And if you write
try(FileReader fr = new FileReader("filename")){
// your code
}
and you are done JVM will automatically close it

There shoud be some kind of destructor. In junit for example (as you are naming your class "test") you have #AfterClass annotation to do your clean-up in such annotated method.

You just close it manually after you use it.
public class PrintWriterDemo {
private PrintWriter writer;
public PrintWriterDemo() {
writer = new PrintWriter(System.out);
}
public void log(String msg) {
writer.write(msg + "\n");
writer.flush();
}
public void close() {
System.out.println("print writer closed.");
writer.close();
}
public static void main(String[] args) {
PrintWriterDemo demo = new PrintWriterDemo();
demo.log("hello world");
demo.close();
}
}

Related

FileWriter not working?

import java.io.IOException;
import java.util.*;
public class Owner {
public static Scanner sc = new Scanner(System.in);
public static void main(String args[]) throws IOException {
String n = sc.nextLine();
Info.namec(n);
}
}
This is the second class, which is supposed to be printing the "HELLO" in the text file.
import java.io.*;
public class Info {
public static void namec(String n) throws IOException//name check
{
File f = new File("TEXT");
FileWriter fw = new FileWriter(f);
fw.write("HELLO!");
}
}
This code is not working, nothing is being typed in the text file.
There are 2 classes, the "Hello" is not being printed.
You don't close the file, and it looks like there is some buffering going on, so nothing gets to the file, as it's so short. Try this:
public static void namec(String n) throws IOException {
File f = new File("TEXT");
try (FileWriter fw = new FileWriter(f)) {
fw.write("HELLO!");
}
}
The so called try-with-resources statement will automatically close the stuff that gets opened in try(), which is generally desirable.
Calling fw.write("String") alone does not guarantee data will be written to file. The data may simply be written to a cache and never get written to the actual file on disk.
I suggest you use below methods,
fw.flush() - Call this when you want data you just wrote to be reflected in the actual file.
fw.close() - Call this when you are done writing all data that needs to be written by calling write method.
Whenever you are using file writer it stores data on cache so you will require for flush and close file writer object.
Here i am adding sample code hope that will help you.
package com.testfilewriter;
import java.io.FileWriter;
public class FileWriterExample {
public static void main(String args[]) {
try {
FileWriter fw = new FileWriter("D:\\testfile.txt");
fw.write("Welcome to stack overflow.");
fw.close();
} catch (Exception e) {
System.out.println(e);
}
System.out.println("File writing complete.");
}
}

Using OutputStream with multiple ObjectOutputStreams?

To abstract from a specific serialization format I thought to define the following:
public interface TransportCodec {
void write(OutputStream out, Object obj) throws IOException;
Object read(InputStream in) throws IOException;
}
A default implementation would use just Java object serialization like this:
public void write(OutputStream out, Object obj) throws IOException {
ObjectOutputStream oout = new ObjectOutputStream(out);
oout.writeObject(obj);
oout.flush();
}
Obviously the oout.close() is missing, but for a reason: I want to be able write several objects into the same stream with independent calls to write. Looking at the source code of ObjectOutputStream (jdk 1.8), oout.close() closes the underlying stream, but also clears data structures that are part of ObjectOutputStream. But since I leave oout right to the garbage collector, I would not expect problems from not closing the stream.
Apart from the risk that a future JDK really needs the oout.close(), two questions:
What do I loose in the current JDK when not closing the ObjectOutputStream above.
First serializing into a ByteArrayOutputStream and then copying the bytes to out would allow to close oout. Are there better options?
Separate into two interfaces and make the implementation class "own" the underlying stream.
Advantages:
Underlying storage is no longer restricted to be an OutputStream / InputStream.
By making the two interfaces extend Closeable, they can now be used in a try-with-resources block.
Caller only need to carry one reference (e.g. TransportEncoder), and will no longer have to carry the stream too (e.g. OutputStream).
Interfaces
public interface TransportEncoder extends Closeable {
void write(Object obj) throws IOException;
}
public interface TransportDecoder extends Closeable {
Object read() throws IOException;
}
ObjectStream implementations
public final class ObjectStreamEncoder implements TransportEncoder {
private final ObjectOutputStream stream;
public ObjectStreamEncoder(OutputStream out) throws IOException {
this.stream = new ObjectOutputStream(out);
}
#Override
public void write(Object obj) throws IOException {
this.stream.writeObject(obj);
}
#Override
public void close() throws IOException {
this.stream.close();
}
}
public final class ObjectStreamDecoder implements TransportDecoder {
private final ObjectInputStream stream;
public ObjectStreamDecoder(InputStream in) throws IOException {
this.stream = new ObjectInputStream(in);
}
#Override
public Object read() throws IOException {
try {
return this.stream.readObject();
} catch (ClassNotFoundException e) {
throw new NoClassDefFoundError(e.getMessage());
}
}
#Override
public void close() throws IOException {
this.stream.close();
}
}

Java: Call a main method from a main method in another class

I have a set of Java files in the same package, each having main methods. I now want the main methods of each of the classes to be invoked from another class step by step. One such class file is Splitter.java. Here is its code.
public static void main(String[] args) throws IOException {
InputStream modelIn = new FileInputStream("C:\\Program Files\\Java\\jre7\\bin\\en-sent.bin");
FileInputStream fin = new FileInputStream("C:\\Users\\dell\\Desktop\\input.txt");
DataInputStream in = new DataInputStream(fin);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine = br.readLine();
System.out.println(strLine);
try {
SentenceModel model = new SentenceModel(modelIn);
SentenceDetectorME sentenceDetector = new SentenceDetectorME(model);
String sentences[] = sentenceDetector.sentDetect(strLine);
System.out.println(sentences.length);
for (int i = 0; i < sentences.length; i++) {
System.out.println(sentences[i]);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (modelIn != null) {
try {
modelIn.close();
} catch (IOException e) {
}
}
fin.close();
}
}
I now want this to be invoked in AllMethods.java inside a main method.
So how can I do this? There are several other class files having main methods with IOException which have to be invoked in AllMethods.java file.
Update -
I have main methods having IOException as well as main methods not having IOEXception that has to be invoked in AllMethods.java.
You can do that. Main method is also just like any other static method
public static void main(String[] args) throws IOException {
....// do all the stuff
Splitter.main(args); // or null if no args you need
}
First of all, what you should probably do is refactor your code so each main method calls some other method, and then AllMethods makes calls to those new methods. I can imagine there might be some cases where it's useful if you're just trying to, for example, write some test code, but usually you wouldn't want to call main methods directly. It's just harder to read.
If you want to try it though, it's pretty easy, you just call the main method like any other static method. I once in college wrote a web server where, to handle authentication, I recursed on the main method. I think I got a C because it was unreadable code, but I had fun writing it.
class AllMethods {
public void callsMain() {
String[] args = new String[0];
Splitter.main(args);
}
}
In the Main.java, the main method should add throws Exception as shown below:
package com.company;
import java.io.FileNotFoundException;
public class Main extends makeFile {
public static void main(String[] args) throws FileNotFoundException {
makeFile callMakeFile = new makeFile();
makeFile.main(args);
// cannot figure out how to call the main method from the makeFile class here...
}
}

Java Code without Try and Catch

I have the code:
public class RssReader {
private File dataFile = new File("data.dat");
private FileInputStream dataStream = new FileInputStream("data.dat");
boolean fileExists;
public static void main(String[] args) {
}
}
My question is, can I put FileInputStream or any code that requires Try/catch as a global function?
Yes you can. you can declare that main method throws an Exception of any kind, i.e.
public static void main(String[] args) throws IOException {
}
And you can omit the try-catch block in the code.
I would highly suggest NOT doing that, though. First of all, try-catch blocks exist for a reason. They are here to catch exceptions that you might foresee but have no control of (i.e. bad file format). Second of all, they will let you close the streams in finally blocks even if the exception happens.
Yes you can if you let your constructor throws the exception :
class RssReader {
private File dataFile = new File("data.dat");
private FileInputStream dataStream = new FileInputStream("data.dat");
boolean fileExists;
RssReader()throws IOException{}
}
Then each time you will construct a new RssReader object, the method that handle this construction should throws it too (like darijan said), or you can create a try-catch block in this method :
public void someMethod() throws IOException {
RssReader r = new RssReader();
}
or :
public void someMethod() {
RssReader r;
try {
r = new RssReader();
} catch (IOException e) {
e.printStackTrace();
}
}
You may add that code by signing the method with throws Exception. But it is not recommended when you have an stream reader or something like that because often you gotta close the stream or flush the writers.
I think you should think about it when you need to open or close a stream object.
There are several things you can do and several you can't:
You can't initialize a variable with code that can throw a checked exception. The compiler will complain. So your line beginning private FileInputStream ... is illegal.
You can't use the instance variables inside the static main() method. The compiler will again complain once you put ... dataStream ... inside main().
You can put a throws IOException on the main method.
One way to deal with these things is to do this:
public class RssReader {
public static void main(String[] args) throws IOException {
File dataFile = new File("data.dat");
FileInputStream dataStream = new FileInputStream("data.dat");
boolean fileExists;
... use the variables here ...
}
}
which will toss you out to the command line if you run the program and, for example, the file doesn't exist. An error message and stack trace will be printed if that happens.
What I did up there is move all the variables into the scope of the main() method. Then I added the throws on the method so it will let whatever basic part of Java calls main() handle the exception.
Or you could do something another way like this:
public class RssReader {
private static File dataFile = new File("data.dat");
private static FileInputStream dataStream;
static {
try {
dataStream = new FileInputStream("data.dat");
} catch (IOException e) {
throw new RuntimeException(e); // this isn't a best practice
}
}
static boolean fileExists;
public static void main(String[] args) {
... use the variables here ...
}
}
which will do the same thing if there is a problem with finding the file. Out to the command line and print messages.
This hides the possible checked exception inside a static initializer block with a try-catch around it. The checked exception is turned into an unchecked exception. It also makes all the variable static so they can be used in the static method main()
One more possible solution that's an even better way:
public class RssReader {
private File dataFile = new File("data.dat");
private FileInputStream dataStream;
boolean fileExists;
public RssReader() throws IOException {
dataStream = new FileInputStream("data.dat");
}
public void doTheWork() {
... use all the variables here ...
}
public static void main(String[] args) {
try {
reader = new RssReader();
reader.doTheWork();
} catch (IOException e) {
System.out.printf("File 'data.dat' not found. Exiting ...");
}
}
}
which is the one I like best. It gives you control over what happens if an exception happens so we print an informative message and tell them the program is finished. All the variables are instance variables inside the object instance created in the main() method. Main does almost nothing but create the instance and tell it to get to work. Main also decides what to do if it fails.
The changes are to move everything to instance scope and out of static scope, except catching the fatal exception. You can leave your variables at the top where they are easy to read. The method that does the work is given a name to describe what it does.

JUnit Testing around Sytem.in and System.out

I have been asked to introduce unit test in a legacy Java Application that runs and operates from Command Line. Basically the main loop prints out a Menu, the user inputs something and it shows more data.
This Main class illustrate how the application works.
public class Main{
static BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
public static void main(String argv[]) throws IOException{
while (true) {
char input = (char) reader.read();
if(input == 'x'){
return;
}
System.out.println(input);
}
}
}
I'd like my test methods to look something like this
public void testCaseOne(){
Main.main();
String result = "";
result = sendInput("1");
assertEqual(result, "1");
result = sendInput("x");
assertEqual(result,"");
}
I am aware of the System.setOut() and System.setIn() methods, but I cannot figure out a way to make the System.setIn() method work in this context, since the reader.read() method is blocking my thread.
Is my test design wrong?
Is there a way to design the sendInput() method to work through the blocking reader.read() call?
I would suggest refactoring the code to allow the input/output streams to be injected, and then you can mock them. If you couuld change it to something like
public class Main{
static BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
public static void main(String argv[]) throws IOException{
new YourClass(reader,System.out).run();
}
}
public class YourClass { // I don't know what your class is actually doing, but name it something appropriate
private final InputReader reader;
private final PrintStream output;
public YourClass(InputReader reader, PrintStream output) {
this.reader = reader;
this.output = ouptut;
}
public void run() {
while (true) {
char input = (char) reader.read();
if(input == 'x')
return;
output.println(input);
}
}
This design does a couple of things:
It takes the logic out of your main class. Typically a main method is really just used for launching an application.
It makes YourClass more easily unit testable. In your tests, you can simply mock out the input/output.
Edit: Update to how this refactoring helps with the blocking IO problem
By making the reader/output injectable as shows above, you don't actually need to use the real System.in and System.out - you can use a mock instead. This eliminates the need to actually have blocking reads.
public void testCaseOne(){
// pseudocode for the mock - this will vary depending on your mock framework
InputReader reader = createMock(InputReader);
// the first time you read it will be a "1", the next time it will be an "x"
expect(reader.read()).andReturn("1");
expect(reader.read()).andReturn("x");
PrintStream stream = createMock(PrintStream);
// only expect the "1" to get written. the "x" is the exit signal
expect(stream.println("1"));
new YourClass(reader,stream).run();
verifyMocks();
}
I would refactor Main so it's easier to test.. like so:
public class Main{
private boolean quit = false;
public static void main(String[] argv) throws IOException {
Main main = new Main();
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
char input = main.readInput(reader);
while (!main.quit()) {
System.out.println(input);
input = main.readInput(reader);
}
}
public char readInput(Reader reader) throws IOException{
char input = (char) reader.read();
if(input == 'x'){
quit = true;
return '\0';
}
return input;
}
public boolean quit(){
return quit;
}
}
Personally, I try to stay away from static variables. If you need one you could always declare it in the main method like above.
Testing the while(true) is pretty much impossible because testing if the while loop never quits would take an infinite amount of time. Then there is the question if you should test the quitting of the loop in the main.quit() == true case. Personally, I would just test the core logic and leave the rest untested:
public class MainTest {
private Main main;
#Before
public void setup(){
main = new Main();
}
#Test
public void testCaseOne() throws IOException{
char result1 = main.readInput(new StringReader("1"));
assertEquals(result1, '1');
assertFalse(main.quit());
char result2 = main.readInput(new StringReader("x"));
assertEquals(result2, '\0');
assertTrue(main.quit());
}
}
Here is the solution I went with that required no refactoring of the legacy code.
In a nutshell, I made an Abstract Test Class that compiles and execute the Application in a Process on a seperate thread. I attach myself to the Input/Output of the Process and read/write to it.
public abstract class AbstractTest extends TestCase{
private Process process;
private BufferedReader input;
private BufferedWriter output;
public AbstractTest() {
//Makes a text file with all of my .java files for the Java Compiler process
Process pDir = new ProcessBuilder("cmd.exe", "/C", "dir /s /B *.java > sources.txt").start();
pDir.waitFor();
//Compiles the application
Process p = new ProcessBuilder("cmd.exe", "/C", "javac #sources.txt").start();
p.waitFor();
}
protected void start(){
Thread thread = new Thread() {
public void run() {
//Execute the application
String command = "java -cp src/main packagename.Main ";
AbstractTest.this.process = = new ProcessBuilder("cmd.exe", "/C", command).start();
AbstractTest.this.input = new BufferedReader(new InputStreamReader(AbstractTest.this.process.getInputStream()));
AbstractTest.this.output = new BufferedWriter(new OutputStreamWriter(AbstractTest.this.process.getOutputStream()));
}
}
}
protected String write(String data) {
output.write(data + "\n");
output.flush();
return read();
}
protected String read(){
//use input.read() and read until it makes senses
}
protected void tearDown() {
this.process.destroy();
this.process.waitFor();
this.input.close();
this.output.close();
}
}
Afterward, it was pretty easy to make actual test class and implement real test methods.
public void testOption3A(){
start();
String response = write("3");
response = write("733");
assertEquals("*** Cactus ID 733 not found ***",response);
}
Pros
No refactoring needed
Actually testing the implementation (No Mocking/Injection)
Doesn't require any external librairies
Cons
Pretty hard to debug when things aren't working proprely (Fixable)
Rely heavily on OS behavior (Windows in this class, but Fixable)
Compiles the application for every test class (Fixable I think?)
"Memory Leak" when there is an error and the process is not killed
(Fixable I think?)
This is probably a borderline "hack", but it met my needs and demands.

Categories