Java static printstream error [duplicate] - java

This question already has answers here:
Java: startingPath as "public static final" exception
(5 answers)
Closed 5 years ago.
Unreported exception java.io.FileNotFoundException; must be
caught or declared to be thrown
I'm writing a basic program to generate a a script. I'm using two methods to write to the file, so, I thought I'd user a static level file and printstream.`
static String fileName = "R1";
static File inputFile = new File(fileName+".txt");
static PrintStream write = new PrintStream(fileName+"_script.txt");
`
It won't run, it asks me to catch or throw. Do I have to add a try-catch clause in the class level and is that even possible?

PrintStream constructor is throwing an exception that you need to catch, but you are not able to handle that if you just do;
static PrintStream write = new PrintStream(fileName + "_script.txt");
so your options are:
try defining a static block
static String fileName = "R1";
static File inputFile = new File(fileName + ".txt");
static {
try {
PrintStream write = new PrintStream(fileName + "_script.txt");
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
or even better define a static method to initialize those objects:
static String fileName;
static File inputFile;
static PrintStream write;
public static void init() throws FileNotFoundException {
fileName = "R1";
inputFile = new File(fileName + ".txt");
write = new PrintStream(fileName + "_script.txt");
}

You can't initialize PrintStream like this, because it should throw an exception so you have to catch this exception, how? you can create a method which can throw this exception for example :
static String fileName;
static File inputFile;
static PrintStream write;
public static void init() throws FileNotFoundException {
//------------------^^-------^^
fileName = "R1";
inputFile = new File(fileName + ".txt");
write = new PrintStream(fileName + "_script.txt");
}
Or even you can catch your exception with :
public static void init() {
fileName = "R1";
inputFile = new File(fileName + ".txt");
try {
write = new PrintStream(fileName + "_script.txt");
} catch (FileNotFoundException ex) {
ex.printStackTrace();
}
}

Related

Equivalent of try-with-resources but throw the exception

I have a function read:
public static ArrayList<String> read(Path path) throws FileNotFoundException {
ArrayList<String> lines = new ArrayList<String>();
File fileToRead = path.toFile();
Scanner fileReader = new Scanner(fileToRead);
while (fileReader.hasNext()) {
lines.add(fileReader.nextLine());
}
fileReader.close();
return lines;
}
I want it to pass on a FileNotFoundException if it encounters one, but I'm not sure if encountering this exception while creating the scanner will result in an unclosed scanner.
I'd like to implement a similar behavior that the try-with-resources block provides as shown below, but without catching and re-throwing the error (unless this is the intended solution).
public static ArrayList<String> read(Path path) throws FileNotFoundException {
ArrayList<String> lines = new ArrayList<String>();
File fileToRead = path.toFile();
try (
Scanner fileReader = new Scanner(fileToRead);
) {
while (fileReader.hasNext()) {
lines.add(fileReader.nextLine());
}
}
catch (FileNotFoundException e) {
throw e;
}
return lines;
}

Want a code to be written without throwing exception

I have the below piece of code.
import java.io.*;
public class FileTest {
public static void main(String[] args) throws IOException {
WriteLinesToFile("miss.txt","This is a special file");
}
public static void WriteLinesToFile(String outputFileName, String lineConverted) throws IOException {
File f = new File(outputFileName);
if (f.createNewFile()) {
System.out.println("File is created!");
FileWriter writer = new FileWriter(f);
writer.write(lineConverted);
writer.close();
} else {
System.out.println("File already exists.");
FileWriter writer = new FileWriter(f);
writer.write(lineConverted);
writer.close();
}
}
}
I need the same logic, without throwing exception. Could someone tell me how to do this?
You could handle your exception with a try{} catch(IOException e){}
But it's important to handle the exception, because otherwise your program will do something, but not what you want.
import java.io.*;
public class FileTest {
public static void main(String[] args)
{
writeLinesToFile("miss.txt", "This is a special file");
}
public static void writeLinesToFile(String outputFileName, String lineConverted){
File f = new File(outputFileName);
try {
if (f.createNewFile()) {
System.out.println("File is created!");
FileWriter writer = new FileWriter(f);
writer.write(lineConverted);
writer.close();
} else {
System.out.println("File already exists.");
FileWriter writer = new FileWriter(f);
writer.write(lineConverted);
writer.close();
}
}
catch(IOException e){
//Handle your error
}
}}
But you can't cut out the exceptions at all, because handling files in java throws always exceptions (For example if the file could not be found).

Junk values getting updated to text file

I am trying to update a file with some value. But there are few junk values are also getting updated with the original content while saving. Using the below code.
public class WriteToFile{
public static void main(String[] args){
Path path = Paths.get("C:\\someFile.txt");
String fileContent = new String("someText");
if (Files.exists(path)) {
final File filePath = new File("C:\\someFile.txt");
try {
FileUtils.writeFile(filePath,fileContent);
} catch (final Exception e1) {
// TODO What if writing to the state file fails??
}
}
}
public class FileUploadUtils {
public static void writeFile(final File filePath, final Object
byteFileContent) {
try (FileOutputStream fileOutputStream = new FileOutputStream(filePath);
ObjectOutputStream out = new ObjectOutputStream(fileOutputStream)) {
out.writeObject(byteFileContent);
} catch (final IOException io) {
io.printStackTrace();
}
}
}
I am able to write the content to file also, but it is adding some junk characters also. like "’ t SomeText"
The ObjectOutputStream seems to add some values while writing the data to the file.
Why won't you directly use the FileOutputStream you created and pass the data as bytes ?
public static void main(String[] args) {
Path path = Paths.get("C:\\someFile.txt");
String fileContent = new String("someText");
if (Files.exists(path)) {
final File filePath = new File("C:\\someFile.txt");
try {
FileUploadUtils.writeFile(
filePath, fileContent.getBytes());
} catch (final Exception e1) {
// TODO What if writing to the state file fails??
}
}
}
public class FileUploadUtils {
public static void writeFile(final File filePath, final byte[] byteFileContent) {
try (FileOutputStream fileOutputStream = new FileOutputStream(filePath)) {
fileOutputStream.write(byteFileContent);
} catch (final IOException io) {
io.printStackTrace();
}
}
}

Don't know how to handle FileWriter exceptions

In my code, one of my methods says:
this.write("stuff")
and the write method is
public void write(String text) throws IOException
{
FileWriter writer = new FileWriter(path, true);
PrintWriter printer = new PrintWriter(writer);
printer.printf("%s" + "%n", text);
printer.close();
}
The thing says that there is an
"unreported exception java.io.IOException; must be caught or declared to be thrown" for the FileWriter.
What should I put in the try and catch statements to fix the exception?
How to handle any kind of exception is essential to Java development.
There is two ways to do it:
public void write(String text) //notice I deleted the throw
{
try{
FileWriter writer = new FileWriter(path, true);
PrintWriter printer = new PrintWriter(writer);
printer.printf("%s" + "%n", text);
printer.close();
catch(IOException ioe){
//you write here code if an ioexcepion happens. You can leave it empty if you want
}
}
and...
public void write(String text) throws IOException //See here it says throws IOException. You must then handle the exception when calling the method
{
FileWriter writer = new FileWriter(path, true);
PrintWriter printer = new PrintWriter(writer);
printer.printf("%s" + "%n", text);
printer.close();
}
//like this:
public static void main(String[] args) //or wherever you are calling write from
{
try{
write("hello"); //this call can throw an exception which must be caught somewhere
}catch(IOException ioe){/*whatever*/}
}

Resolving IOException, FileNotFoundException when using FileReader

I've not been able to resolve the following exception in the code below. What is the problem with the way I use BufferedReader? I'm using BufferedReader inside the main method
OUTPUT :-
ParseFileName.java:56: unreported exception java.io.FileNotFoundException; must be caught or declared to be thrown
BufferedReader buffread = new BufferedReader (new FileReader("file.txt"));
// ParseFileName is used to get the file name from a file path
// For eg: get - crc.v from "$ROOT/rtl/..path/crc.v"
import java.util.regex.Pattern;
import java.io.*;
public class ParseFileName {
//Split along /'s , and collect the last term.
public String getName (String longName) {
String splitAt = "/";
Pattern pattern1 = Pattern.compile(splitAt);
String[] parts = pattern1.split(longName);
System.out.println("\nparts.length = " + parts.length);
//Return the last element in the array of strings
return parts[parts.length -1];
}
public static void main(String[] args) {
ParseFileName superParse = new ParseFileName();
BufferedReader buffread = new BufferedReader (new FileReader("file.txt"));
String line;
while ((line = buffread.readLine())!= null) {
String fileName = superParse.getName(line);
System.out.println("\n" + line + " => " + fileName);
}
buffread.close();
}
}
UPDATE :
The following works:
public static void main(String[] args) throws FileNotFoundException, IOException {
However try.. catch still has some nagging issues for me:
try {
BufferedReader buffread = new BufferedReader (new FileReader("file.txt"));
} catch (FileNotFoundException ex) {
ex.printStackTrace();
} catch (IOException ex2) {
ex2.printStackTrace();
}
buffread dosent seem to get the file name. I get this error:
javac ParseFileName.java ParseFileName.java:67: cannot resolve symbol
symbol : variable buffread
location: class ParseFileName
while ((line = buffread.readLine())!= null) {
Add throws FileNotFoundException, IOException in the header of your method. It looks like just throwing the IOException will solve your problem, but incorporating both will allow you to tell if there was a problem with the file's existence or if something else went wrong (see catch statements below).
i.e.
public static void main(String[] args) throws FileNotFoundException, IOException {
Alternately, if you'd like to catch a specific exception and do something with it:
try {
BufferedReader buffread = new BufferedReader (new FileReader("file.txt"));
} catch (FileNotFoundException ex) {
// Do something with 'ex'
} catch (IOException ex2) {
// Do something with 'ex2'
}
Update to resolve the updated issue: This is just a simple scope problem which can be solved by declaring the BufferedReader outside of the try statement.
BufferedReader buffread = null;
try {
buffread = new BufferedReader (new FileReader("file.txt"));
} catch (FileNotFoundException ex) {
...
You have to add throws statement into the signature of method main or wrap code in
try {
...
} catch (FileNotFoundException e) {
...
}
Your code can throw FileNotFoundException or IOException which is Checked Exception. You need to surround your code in a try-catch block or add a throws declaration in your main function.
The BufferReader can throw an exception if the file cannot be found or opened correctly.
This error message is telling you that you need to handle this exception. You can wrap the line where you create the BufferReader in a try/catch block. This will handle the case an IOException is thrown and print out the stack trace.
public static void main(String[] args) {
ParseFileName superParse = new ParseFileName();
BufferedReader buffread;
try
{
buffread= new BufferedReader (new FileReader("file.txt"));
}
catch(FileNotFoundException e)
{
e.printStackTrace();
}
String line;
while ((line = buffread.readLine())!= null) {
String fileName = superParse.getName(line);
System.out.println("\n" + line + " => " + fileName);
}
buffread.close();
}
Another option is to add "throws IOException" to your method header.
public static void main(String[] args) throws IOException {
//...
}
This tells the compiler and callers of your method that you are choosing to not handle this exception and there is a chance it will be thrown.

Categories