Declaring a static FileWriter and FileReader - java

I want to declare a static FileWriter and FileReader instance so I can use the same one throughout a large program. Eclipse tells me that an IOException must be thrown. How can I throw an exception for the declaration?
static FileWriter fileWriter = new FileWriter(file, true);
static BufferedWriter writer = new BufferedWriter(fileWriter);
static FileReader fileReader = new FileReader(file);
static BufferedReader reader = new BufferedReader(fileReader);
Thanks.

Try something like this:
static File file = new File("");
static FileWriter fileWriter;
static BufferedWriter writer;
static FileReader fileReader;
static BufferedReader reader;
static {
try {
fileWriter = new FileWriter(file, true);
writer = new BufferedWriter(fileWriter);
fileReader = new FileReader(file);
reader = new BufferedReader(fileReader);
} catch (final IOException e) {
throw new ExceptionInInitializerError(e.getMessage());
}
}

Just put a throws IOException after the method declaration.
i.e.: public static void main(String[] args) throws IOException { ... }
That's it.
Though it is not elegant to use it this way...

Put the initialization in a static block as follows:
public final class MyUtil {
static FileWriter fileWriter;
static BufferedWriter writer;
static FileReader fileReader;
static BufferedReader reader;
static {
try {
File file = new File("<pathToFile>");
fileWriter = new FileWriter(file, true);
writer = new BufferedWriter(fileWriter);
fileReader = new FileReader(file);
reader = new BufferedReader(fileReader);
}
catch (IOException e) {
// Handle the exception here
}
}
}
Note that this will kind of global state to a file writer/reader can cause issues in a multi-threaded environment, so you might want to make sure there is some synchronization to handle this.

Related

How to process files for unit testing?

I have 5 input files in a folder, for each input file (1.in for example), I process it and produce a new output file (1.out) printing a integer in it.
How do I do this?
Right now this is what I have, I want to run different files like a2.in and print output in new file like a2.out (name them based on the input file names).
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new FileReader("a1.in"));
PrintWriter pw = new PrintWriter(new BufferedWriter(new FileWriter("a1.out")));
public int compareTo(Event a) {
return ans;
}
That depends on unit test and assertion library you are using, below is example for junit-jupiter akin junit5 and assertJ:
#ParameterizedTest
#CsvSource(delimiterString = ";", value = {"a1.in;a1.out", "a2.in;a2.out""})
void test(String input, String output) throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try (InputStream in = getStream(input); InputStream expected = getStream(output)) {
// test body reading from in and writing to baos
assertThat(new ByteArrayInputStream(baos.toByteArray()))
.hasSameContentAs(expected);
}
}
InputStream getStream(String resource) {
return getClass().getResourceAsStream("/" + resource);
}
UPD (Thanks Reinier for comments).
If your goal is to test #main method (i.e. you are writing CLI application, which reads and writes some files) and your #main method looks like:
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new FileReader(args[0]));
PrintWriter pw = new PrintWriter(new BufferedWriter(new FileWriter(args[2])));
// do something with br and pw
}
consider redesigning it to something like:
public static void main(String[] args) throws IOException {
main(Files.newInputStream(Paths.get(args[0])), Files.newOutputStream(Paths.get(args[1])));
}
public static void main(InputStream in, OutputStream out) throws IOException {
try (
BufferedReader br = new BufferedReader(new InputStreamReader(in));
PrintWriter pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(out);
) {
// do something with br and pw
pw.flush();
}
}
in that case the testability of #main method gets improved.

Read file name from user input on linux terminal - JAVA

I want to make a little script in JAVA to receive a file name in the linux terminal and read that file.
This is what i'm trying:
import java.util.Scanner;
import java.io.*;
class ItauScript {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
System.out.println("Filename: ");
String fileName = reader.next();
FileReader fileReader = new FileReader(fileName);
BufferedReader bufferedReader = new BufferedReader(fileReader);
System.out.println(bufferedReader.readLine());
}
}
But the code doesn't compile. I get this error message:
hello.java:10: error: unreported exception FileNotFoundException; must
be caught or declared to be thrown
FileReader fileReader = new FileReader(fileName);
^ hello.java:13: error: unreported exception IOException; must be caught or declared to be thrown
System.out.println(bufferedReader.readLine());
I can open the file if i put it on hardcode on a string.
But i need to receive it as an input from the terminal.
What am i missing?
Try:
import java.util.Scanner;
import java.io.*;
class ItauScript {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
System.out.println("Filename: ");
String fileName = reader.next();
try {
FileReader fileReader = new FileReader(fileName);
BufferedReader bufferedReader = new BufferedReader(fileReader);
System.out.println(bufferedReader.readLine());
} catch (IOException e) {
// handle exception (if any) here
}
}
}
And as others suggested, it's very helpful to read what the IDE/Compiler tells you in case of errors ...
Hope that helps
FileNotFoundException is a checked Exception (as is the parent class IOException thrown by readLine), modify main to re-throw1 it like
public static void main(String[] args) throws IOException {
or surround it with a try-catch (with resources) like
try (FileReader fileReader = new FileReader(fileName);
BufferedReader bufferedReader = new BufferedReader(fileReader)) {
System.out.println(bufferedReader.readLine());
} catch (IOException e) {
e.printStackTrace();
}
1But you should still close the bufferedReader in a finally.
You need to handle the possible exception. You can specify that the enclosing method main throws the exception, but it would be better to handle it yourself.
import java.util.Scanner;
import java.io.*;
class ItauScript {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
try
{
System.out.println("Filename: ");
String fileName = reader.next();
FileReader fileReader = new FileReader(fileName);
BufferedReader bufferedReader = new BufferedReader(fileReader);
System.out.println(bufferedReader.readLine());
}
catch(IOException e)
{
e.printStackTrace();
//TODO handle error
return;
}
}
}

Error in File I/O

I just started doing file I/O andim using an example from Murach's Se 6.
Here is my code. Am i missing something. I know the code further on has more but as this is an example this should work right?
//Import import java.io.*; for use with the File I/O Methods.
import java.io.*;
public class MainApp
{
public static void main(String[] args)
{
//Create a file object.
File productFile = new File("product.txt");
//Open a buffered output stream to allow write to file operations.
PrintWriter out = new PrintWriter(
new BufferedWriter(
new FileWriter(productFile)));
out.println("java\tMurach's Beginning Java 2\t$49.99");
out.close();
BufferedReader in = new BufferedReader(
new FileReader(productFile));
String line = in.readLine();
System.out.println(line);
out.close();
}
}
//Answer
by adding a throws exception to the end of where i initialised the main this code works. Even the txt file products.txt is in the class folder as expected.
//Import import java.io.*; for use with the File I/O Methods.
import java.io.*;
public class MainApp
{
public static void main(String[] args) throws Exception
{
//Create a file object.
File productFile = new File("product.txt");
//Open a buffered output stream to allow write to file operations.
PrintWriter out = new PrintWriter(
new BufferedWriter(
new FileWriter(productFile)));
out.println("java\tMurach's Beginning Java 2\t$49.99");
out.close();
BufferedReader in = new BufferedReader(
new FileReader(productFile));
String line = in.readLine();
System.out.println(line);
out.close();
}
}
The problem is that a number of the calls to the java.io package throw exceptions.
easy fix: add the following to your method signature
public static void main(String[] args) throws IOException
almost as easy fix: add try/catch/finally blocks.
public static void main(String[] args)
{
//Create a file object.
File productFile = new File("product.txt");
//Open a buffered output stream to allow write to file operations.
PrintWriter out = null;
try {
out = new PrintWriter(
new BufferedWriter(
new FileWriter(productFile)));
out.println("java\tMurach's Beginning Java 2\t$49.99");
}
catch(IOException ex) {
// todo exception handling
System.out.println("ERROR! " + ex);
}
finally {
out.close();
}
BufferedReader in = null;
try {
in = new BufferedReader(
new FileReader(productFile));
String line = in.readLine();
System.out.println(line);
}
catch (IOException ex) {
// todo more exception handling
System.out.println("ERROR! " + ex);
}
finally {
in.close();
}
}
edit: you know you are trying to call out.close() twice? The second should be a call to in.close()

This program neither reads nor writes to a file

CODE
import java.io.*;
class tester {
public static void main(String args[]) {
try {
FileReader reader = new FileReader(new File("d:\\UnderTest\\check123.txt"));
FileWriter writer = new FileWriter(new File("d:\\UnderTest\\check123.txt"));
BufferedReader br = new BufferedReader(reader);
String s;
while( (s=br.readLine()) != null ) {
System.out.println(s);
}
writer.write("Shadow Shadow");
} catch(Exception exc) {
System.out.println(exc);
}
}
}
This code writes nothing and reads nothing when i run it. Where is the bug in this program ?
Are you sure that when you read for first time then content is there in the text file ?
You need to close Reader and Writer in finally block (missing currently in your code) of your try-catch block. closing the stream flushes out content automatically.
Make sure you close the reader and the writer. After using the writer you will need to flush the contents or close the writer (which does the same thing). I tested this and it works.
import java.io.*;
class tester {
public static void main(String args[]) {
try {
FileReader reader = new FileReader(new File("c:\\check123.txt"));
FileWriter writer = new FileWriter(new File("c:\\check123.txt"));
BufferedReader br = new BufferedReader(reader);
writer.write("Shadow Shadow");
writer.close();
String s;
while( (s=br.readLine()) != null ) {
System.out.println(s);
}
reader.close();
} catch(Exception exc) {
System.out.println(exc);
}
}
}

java write data to file without erasing the old content

how can i
write data to file without erasing the old content
Use new FileOutputStream(file, true). This will open file in "append" mode which will append all data written to the stream to the end of that file.
You mean "how do you append to a file"? Look for an [append-version of a constructor][1] of your File writing class, e.g.:
public FileWriter(String fileName,
boolean append)
throws IOException
Use this constructor and pass true for the append parameter.
[1]: http://download.oracle.com/javase/6/docs/api/java/io/FileWriter.html#FileWriter(java.io.File, boolean)
if you used the new one in Java 7, you can use this way
try (BufferedWriter writer = Files.newBufferedWriter(outFile, StandardCharsets.UTF_8, StandardOpenOption.APPEND))
in this code i use append (true) but my old date erase and new data overwrite on it please give me solution on it
public class FileOperation {
private static FileReader fileReader;
private static FileWriter fileWriter;
private static BufferedReader bufferedReader;
private static BufferedWriter bufferedWriter;
private static PrintWriter writer;
public static File file = new File("C:\\StudentInfo\\com\\education\\students\\file\\managing\\v1_0\\Student.txt");
public FileOperation() throws IOException {
fileReader = new FileReader(file);
fileWriter = new FileWriter(file, true);
bufferedReader = new BufferedReader(fileReader);
bufferedWriter = new BufferedWriter(fileWriter);
// FileOperation fo =new FileOperation();
}
public boolean enrollSudnents(ArrayList<Student> studentList) {
try {
writer = new PrintWriter(file);
writer.print("");
bufferedWriter = new BufferedWriter(new FileWriter(file));
for (Student s : studentList) {
String nameNumberString = String.valueOf(s.getRoll() + "!" + s.getFirstName() + "!" + s.getLastName()
+ "!" + s.getClassName() + "!" + s.getAddress() + "\n");
bufferedWriter.write(nameNumberString);
}
return true;
} catch (Exception e) {
return false;
} finally {
try {
bufferedWriter.close();
fileWriter.close();
} catch (Exception e) {
// logger.info("Exception Found In Adding data");
}
}
}

Categories

Resources