I'm trying to output the squares of the numbers 1-10 to a file named Squares but i'm having an error with the OutputStream.print(i+"\t"+(i*i)); part. The print is being underlined and i can't understand why. Please help me.
Here's the codes:
import java.util.*;
import java.io.*;
public class Number1 {
public static void main(String[] args) throws FileNotFoundException {
FileOutputStream fos = new FileOutputStream("Squares.txt");
PrintWriter square;
try{
square = new PrintWriter(fos);
} catch (Exception e) {
System.out.print("Could not create/open file");
System.exit(0);
}
for(int i=1; i<=10; i++)
{
OutputStream.print(i+"\t"+(i*i));
}
}
}
Complete solution:
import java.io.*;
public class Number1 {
public static void main(String[] args) throws FileNotFoundException {
FileOutputStream fos = new FileOutputStream("Squares.txt");
PrintWriter square = null;
try{
square = new PrintWriter(fos);
}
catch (Exception e)
{
System.out.print("Could not create/open file");
System.exit(0);
}
for(int i=1; i<=10; i++)
{
square.print(i+"\t"+(i*i));
}
square.close();
}
}
OutputStream has no print method ,and even if it had one, it would probably not be a static method.
Use your PrintWriter instance to write to the file.
public static void main(String[] args) throws FileNotFoundException
{
FileOutputStream fos = new FileOutputStream("Squares.txt");
try{
PrintWriter square = new PrintWriter(fos);
for(int i=1; i<=10; i++) {
square.print(i+"\t"+(i*i));
}
square.close ();
}
catch (Exception e) {
System.out.print("Could not create/open file");
System.exit(0);
}
}
You have to call square.print(i+"\t"+(i*i)); instead of OutputStream.print(i+"\t"+(i*i));
You are calling print on the class OutputStream rather than on an instance of a class that has that function. What you probably want to do is
square.print(i+"\t"+(i*i));
To quickly make your code to work,
move the for loop into the try{} statement, and also instead of wrongly calling the OutputStream.print, use the command: square.print
You should use fos.write((i+"\t"+(i*i)).getBytes());
Related
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).
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 found the code below from the internet, works but it doesn't write the printed console to omt.txt, it only writes the System.out.println statements after the second catch block.If you run the code once you will understand what I mean.All I want is to write what is on console to the "omt.txt" file that is all...
After some answers, I see that my question wasn't clear, sorry for that.
I want to save console output to omt.txt text file. If on the console "Hello 123" is printed , it should be also in omt.txt file.In other words whatever on the console is printed should be simultaneously written on the om.txt file or can be after the console execution but should be 1-to-1 the same!
import java.io.File;
import java.io.FileOutputStream;
import java.io.PrintStream;
public class Wrt_file {
public static void main(String[] args) {
System.out.println("THIS is what I see on the console. but not on TEXT file");
File f = new File("omt.txt");
if(!f.exists())
{
try {
f.createNewFile();
} catch (Exception e) {
e.printStackTrace();
}
}
try {
FileOutputStream fos = new FileOutputStream(f);
PrintStream ps = new PrintStream(fos);
System.setOut(ps);
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("THIS is what I see on the text file, but not on CONSOLE");
for (int i=0; i<10; i++){
System.out.println("Testing");
}
}
}
Updated answer after learning that OP wants to duplicate streams
Since you want to write data in both streams try using TeeOutputStream from Apache Commons. Change your code in second try to
try {
FileOutputStream fos = new FileOutputStream(f);
Runtime.getRuntime().addShutdownHook(new Thread(() -> {
try {
fos.flush();
}
catch (Throwable t) {
// Ignore
}
}, "Shutdown hook Thread flushing " + f));
//we will want to print in standard "System.out" and in "file"
TeeOutputStream myOut=new TeeOutputStream(System.out, fos);
PrintStream ps = new PrintStream(myOut, true); //true - auto-flush after println
System.setOut(ps);
} catch (Exception e) {
e.printStackTrace();
}
Now results from System.out will also be placed in your file.
The reason is :
The java.lang.System.setOut() method reassigns the "standard" output stream.
so when you use System.out.println it will print only in the text file
So , if you want to print on the text file and on the console , Try this :
FileOutputStream fos = new FileOutputStream(f);
PrintStream ps = new PrintStream(fos);
ps.println("THIS is what I see on the text file, but not on CONSOLE");
System.out.println("THIS is what I see on the text file, but not on CONSOLE");
for (int i = 0; i < 4; i++) {
ps.println("Testing");
System.out.println("Testing");
}
My solution to this problem is to simply define your own PrintStream which overrides the methods you are using:
import java.io.FileNotFoundException;
import java.io.PrintStream;
public class DualStream extends PrintStream {
public PrintStream consoleOutput = null;
public PrintStream fileOutput = null;
public DualStream(final PrintStream consoleOutput, final PrintStream fileOutput) throws FileNotFoundException {
super(fileOutput, true);
this.consoleOutput = consoleOutput;
this.fileOutput = fileOutput;
}
#Override
public void println() {
consoleOutput.println();
super.println();
}
#Override
public void println(final Object output) {
consoleOutput.println(output);
super.println(output);
}
#Override
public void println(final String output) {
consoleOutput.println(output);
super.println(output);
}
#Override
public PrintStream printf(final String output, final Object... variables) {
consoleOutput.printf(output, variables);
super.printf(output, variables);
return this;
}
}
Every method we don't override will default to writting the output to the file only. (To default to console you can switch 1 line in the Constructor or switch both printstreams position in the constructor call)
Now simply define 2 printstreams, one of which will be writting to your file, let's make it a bufferedoutputstream to ensure good performance aswell:
public static void outputFile(final String file) {
PrintStream CombinedOutput = null;
try {
CombinedOutput = new DualStream(System.out, new PrintStream(new BufferedOutputStream(new FileOutputStream(file))));
} catch (final FileNotFoundException e) {
e.printStackTrace();
}
System.setOut(CombinedOutput);
}
In System.java, this is the declaration of the out property:
public final static PrintStream out
You'll see that it can only be one PrintSteam object at a time. So it's either the console or the file, but not both.
At this line, you have effectively re-channelled the destination:
System.setOut(ps);
So your output stops displaying on the console.
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() )