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).
Related
It's not showing any error but the content should be saved to my file, which is not saving...
import java.util.Scanner;
import java.io.*;
import java.util.logging.Level;
import java.util.logging.Logger;
public class FileReadLine {
public static void main(String[] args) {
try {
String str;
Scanner sc=new Scanner(System.in);
do {
System.out.println("Enter your lines");
str=sc.nextLine();
FileWriter fw = new FileWriter("C:/test/abcd.txt");
if(!str.equals("stop"))
fw.write(str);
fw.write("\n");
fw.close();
} while(!str.equals("stop"));
} catch (Exception ex) {
System.out.println(ex);
}
}
}
please correct my code if i am wrong
You are trying to create a new file inside the loop. So it gets overridden. Change the program to create the file once(before loop) and use it inside the loop to write it.
Also do not close the file as soon as you have written it. Use it once you encounter "stop". Close() should be used when you are done with writing into the file.
Try using flush() before close() to send all data in the buffer to the the file.
You must close you FileWriter (fw) out of while loop.
Try below code
public static void main(String[] args) throws IOException {
FileWriter fw = null;
try {
fw = new FileWriter("C:/Users/MYPC/Desktop/abcd.txt");
String str;
Scanner sc = new Scanner(System.in);
do {
System.out.println("Enter your lines");
str = sc.nextLine();
if (!str.equals("stop")){
fw.write(str);
}
fw.write("\n");
} while (!str.equals("stop"));
} catch (Exception ex) {
System.out.println(ex);
// Logger.getLogger(FileReadLine.class.getName()).log(Level.SEVERE,
// null, ex);
}finally{
if(fw != null){
fw.close();
}
}
}
You were closing the writer in every iteration since you are not using braces in the if condition...
Try this solution, is working
try {
String str;
Scanner sc=new Scanner(System.in);
File fw = new File("C:/Users/MYPC/Desktop/abcd.txt");
FileOutputStream fos = new FileOutputStream(fw);
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(fos));
do {
System.out.println("Enter your lines");
str=sc.nextLine();
if(!str.equals("stop")) {
bw.write(str);
bw.newLine();
} else {
bw.close();
}
} while(!str.equals("stop"));
} catch (Exception ex) {
System.out.println(ex);
}
I want to convert my IO Class from java on Eclipse to the Android API. For some reason it's not working on android!It is giving me a NullPointerException on my Println method. This class is used to create, write, read and open textfiles. My goal is to make all these methods readable on android.
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintStream;
import java.io.PrintWriter;
public class IO {
private static PrintWriter fileOut;
private static BufferedReader fileIn;
public static void createOutputFile(String fileName) {
try {
fileOut = new PrintWriter(new BufferedWriter(new FileWriter(fileName)));
} catch (IOException e) {
System.out.println("*** Cannot create file: " + fileName + " ***");
}
}
public static void openOutputFile(String fileName) {
try {
fileOut = new PrintWriter(new BufferedWriter(new FileWriter(fileName, true)));
} catch (IOException e) {
System.out.println("*** Cannot open file: " + fileName + " ***");
}
}
public static void openOutputFile2(String fileName) {
try {
fileOut = new PrintWriter(new BufferedWriter(new FileWriter(fileName, false)));
} catch (IOException e) {
System.out.println("*** Cannot open file: " + fileName + " ***");
}
}
public static void print(String text) {
fileOut.print(text);
}
public static void println(String text) {
fileOut.println(text);
//System.out.println(text);
}
public static void closeOutputFile() {
fileOut.close();
}
public static void openInputFile(String fileName) {
try {
fileIn = new BufferedReader(new FileReader(fileName));
//System.out.println("opening " + fileName);
} catch (FileNotFoundException e) {
System.out.println("***Cannot open " + fileName + "***");
}
}
public static String readLine()
// throws IOException
// Note: if there's an error in this method it will return IOException
{
try {
return fileIn.readLine();
} catch (IOException e) {
e.printStackTrace();
return "errors";
}
}
public static void closeInputFile() {// throws IOException
// Note: if there's an error in this method it will return IOException
try {
fileIn.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
If you're getting a NullPointerException in println then that would be because 'fileOut' is null.
public static void println(String text) {
fileOut.println(text);
//System.out.println(text);
}
You're actually reacting on your second error because you've ignored the first one. In all cases where you set fileOut you're swallowing (effectively hiding) the error. E.g.
public static void openOutputFile(String fileName) {
try {
fileOut = new PrintWriter(new BufferedWriter(new FileWriter(fileName, true)));
} catch (IOException e) {
//Don't do this, it makes debugging much more difficult.
//Because the root problem is hidden.
//So now you have 2 problems to solve.
//And you've thrown away the information that might have
//helped to solve the problem in the first place.
System.out.println("*** Cannot open file: " + fileName + " ***");
}
}
Stop hiding errors, if something goes wrong you need to find out about it. Because invariably, ignoring errors results in more complex errors later down the line.
Fix you bad exception handling, and you'll be able to track down the root problem (probably file not found or a permission error).
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*/}
}
I have a valet class method that should write an hourly wage to a file:
public void hourlyOverall() throws FileNotFoundException
{
PrintWriter out = new PrintWriter("wage info");
new FileOutputStream("wage info", true);
hourlyOverall = tips / hours + hourlyWage;
out.println(hourlyOverall);
}
However, when I run valet.hourlyOverall() in my main method, the file "wage info" is created but nothing is written to it. What am I doing wrong?
First of all use try-catch for Exception handling and then in the finally block close the OutputStream
out.flush();
Somthing like this
try {
PrintWriter out = new PrintWriter("wage info");
hourlyOverall=tips/hours+hourlyWage;
out.println(hourlyOverall);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
finally {
out.flush();
}
I think this is another way to solve your problem, but using another classes
public class valet {
public static void main(String []args)throws IOException
{
try
{
hourlyOverall()
}
catch(IOException ex)
{
System.out.println(ex+"\n");
}
}
public void hourlyOverall() throws IOException
{
FileWriter out = new FileWriter("wage info");
hourlyOverall=tips/hours+hourlyWage;
out.write(hourlyOverall+"\r\n");
out.close();
}
}
You probably shouldn't declare an anonymous FileOutputStream and you should probably close your PrintWriter,
PrintWriter out=new PrintWriter("wage info");
// new FileOutputStream("wage info",true);
hourlyOverall=tips/hours+hourlyWage;
out.println(hourlyOverall);
out.close(); // <-- like that
Do something like this (if java7 or above) :
public void hourlyOverall()
{
try (PrintWriter out=new PrintWriter("wage info")){
//new FileOutputStream("wage info",true);
hourlyOverall=tips/hours+hourlyWage;
out.println(hourlyOverall);
}catch (FileNotFoundException e) {
e.printStackTrace();
}
}
http://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html
I'm successfully able to read from and write to a sample text file in Java. However, when I try to read from the file, it always throws a NoSuchElementException when it reaches the end of the file. I've modified the code to catch this exception by printing "Reached end of file," but I was wondering if that was normal; I don't feel like it is and I feel like I'm missing something.
Any help is appreciated. Here is my code:
MyFileWriter.java
import java.io.*;
public class MyFileWriter {
public static void main(String[] args) {
File file = new File("MyFile.txt");
PrintWriter out = null;
try {
out = new PrintWriter(file);
out.write("This is a text file.");
} catch(IOException e) {
e.printStackTrace();
System.out.println("IOException: " + e.getMessage());
} finally {
out.flush();
out.close();
}
}
}
MyFileReader.java
import java.io.*;
import java.util.*;
public class MyFileReader {
public static void main(String[] args) {
File file = new File("MyFile.txt");
Scanner scan = null;
try {
scan = new Scanner(file);
while(true) {
String next = scan.nextLine();
if(next != null) {
System.out.println(next);
}
else {
break;
}
}
} catch(IOException e) {
e.printStackTrace();
System.out.println("IOException: " + e.getMessage());
} catch(NoSuchElementException e) {
System.out.println("***Reached end of file***");
} finally {
scan.close();
}
}
}
Instead of while(true) in the reader, use while( scan.hasNextLine() )