Output file is only showing last line of the input file - java

In the output file "CMFTSwitchesnew.txt" only has the last line of the input file. I've tested a few different methods such as changing write.println(input.nextLine()) but I'm not sure now where the issue is.
package WorkingWithFiles;
import java.io.*;
import java.util.Scanner;
public class FileIO
{
public static void main(String[] args)
{
File output = new File("CMFTSwitchesNew.txt");
File source = new File("src/CMFTSwitches.txt");
try {
Scanner input = new Scanner(source);
while (input.hasNextLine()) {
try {
PrintWriter write = new PrintWriter(output);
String text = input.nextLine();
write.println(text) // also tried
// write.println(input.nextLine());
write.close();
} catch (Exception e) {
System.out.println("Exception found");
}
}
} catch (FileNotFoundException e) {
System.out.println("The file was not found");
}
}
}

try {
PrintWriter write = new PrintWriter(output);
String text = input.nextLine();
write.println(text) // also tried
// write.println(input.nextLine());
write.close();
} catch (Exception e) {
System.out.println("Exception found");
}
You're creating a PrintWriter in each iteration without using the constructor that allows you to tell the PrintWriter to append data at the end of an already existing file. That way you only see the output of the last time the file was written. Either change that to
PrintWriter write = new PrintWriter(output, true);
or instantiate the PrintWriter outside the while-loop and close it after it.

Related

Not receiving the reversed text in java file handling

I am trying to create a new file that write a string to a file. Then , I read that file and reverse the text in the file and store the text in my new file.
This is my codes
package OpenFile;
import java.io.*;
import java.util.Scanner;
public class inversetext {
public static void main(String[] args){
try {
ObjectOutputStream file = new ObjectOutputStream(new FileOutputStream("testio.txt"));
file.writeUTF("ABCDEFHIJK");
file.close();
} catch (Exception e) {
System.out.println("File cannot be created");
}
try {
Scanner input = new Scanner(new FileInputStream("testio.txt"));
ObjectOutputStream newfile = new ObjectOutputStream(new FileOutputStream("reverse.txt"));
while (input.hasNextLine()){
String read = input.nextLine();
for (int x= read.length()-1 ; x>=0 ;x--){
newfile.write(read.charAt(x));
}
}
newfile.close();
} catch (Exception e) {
System.out.println("File cannot write");
}
}
}
However , I am not receiving the intended output.
This is how my testio.txt file looks like:
’ w
ABCDEFGHIJK
But this is how my reverse.txt file looks like:
Ԁቷշ䮬䥊䝈䕆䍄䅂
So , my question is:Why am I not getting the reverse text but I got all this characters?

Why fileWriter is not saving the content to my file?

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);
}

BufferedWriter writing to console instead of text file

These are the contents of the constructor of a class which is called by the main method.
File f = null;
Scanner s;
try {
f = new File(getClass().getResource("/LOL.txt").toURI());
} catch (URISyntaxException e) {
e.printStackTrace();
}
try {
s = new Scanner(f);
while(s.hasNextLine()) System.out.println(s.nextLine());
} catch (FileNotFoundException e) {
e.printStackTrace();
}
try {
FileWriter fw = new FileWriter(f.getAbsoluteFile(), false);
BufferedWriter bw = new BufferedWriter(fw);
bw.write("LOL");
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
Output in the console:
LOL
The contents of the file remain unchanged even after repeated runs. My IDE is eclipse
You parametrize your FileWriter with boolean append set as false.
Therefore, the same file will be written over every time that given constructor is executed, and "LOL" will be printed in it.
Before printing "LOL", a Scanner reads each line and prints it, hence the LOL printed in our system out.
Also note, you probably want to declare your FileWriter and BufferedWriter out of the try block, so you can flush and close them in a finally block.
This post only contains the initial question, as-is with everything corrected to avoid several resource-related bugs. It assumes Java 6 or lower.
I shouldn't get any upvote so please don't ;)
package so39452286;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.Writer;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
new Main().run();
}
public void run() {
try {
File file = new File(getClass().getResource("/LOL.txt").toURI());
Scanner scanner = null;
try {
scanner = new Scanner(file);
while (scanner.hasNextLine()) {
System.out.println(scanner.nextLine());
}
} finally {
if (scanner != null) {
scanner.close();
}
}
Writer writer = null; // Holds the main resource, not the wrapping ones.
try {
writer = new FileWriter(file.getAbsolutePath(), false);
BufferedWriter bw = new BufferedWriter(writer);
bw.write("LOL");
bw.flush(); // You forgot to flush. Ok, close() does it, but it's always better to be explicit about it.
} finally {
if (writer != null) {
writer.close();
}
}
} catch (Exception e) {
// Do something with e.
e.printStackTrace(System.err);
}
}
}

Java Input Output Stream can't read the file

I really need help with Java io manipulation of Streams. I don't know why this won't show me the contents of the file. I need to be able to view the text in this binary file "Data.abc" If I can view the contents of this file, i need to create a switch case condition to display it's contents per row / column.
Everytime I run the program, it returns some weird letters and characters like � NAme Address�����
Please help. I'm new to manipulation of streams. Thanks.
package IO_ReadFile;
import java.io.*;
public class ReadFile {
public static void main(String[] args) {
InputStream istream; // creates an Input Stream and named it "istream"
OutputStream ostream; // creates an Output Stream and named it "ostream"
File inputFile = new File("Data.abc"); //passes file as argument
int c;
final int EOF=-1;
ostream = System.out;
try
{
istream = new FileInputStream(inputFile);
try
{
while((c=istream.read()) !=EOF)
ostream.write(c);
}
catch(IOException e)
{
System.out.println("Error: " + e.getMessage());
}
finally
{
try
{
istream.close();
ostream.close();
}
catch(IOException e)
{
System.out.println("File did not close");
}
}
}
catch(FileNotFoundException e)
{
System.exit(1);
}
}
}

Not 100% sure on Try /Catch

I have been asked to convert this code with a throw exception IF to a try/catch block. I have set it up but am not sure what to put in lieu of the word output so that it may run. I am not sure after reading the book and oracles info try/catch I see what needs to be done so the txt file will print. I will post code to be modified and then my change with try/catch. thanks for any help.
public class WriteData {
public static void main(String[] args) throws Exception {
java.io.File file = new java.io.File("scores.txt");
if (file.exists()) {
System.out.println("File already exists");
System.exit(0);
}
// Create a file
java.io.PrintWriter output = new java.io.PrintWriter(file);
// Write formatted output to the file
output.print("John T Smith ");
output.println(90);
output.print("Eric K Jones ");
output.println(85);
// Close the file
output.close();
}
}
Here is the code changed for the Try/Catch
import java.io.FileNotFoundException;
public class WriteData {
public static void main(String[] args) {
java.io.File file = new java.io.File("scores.txt");
try {
output = new java.io.PrintWriter(file);
} catch (FileNotFoundException ex) {
ex.printStackTrace();
}
// Create a file
java.io.PrintWriter output = new java.io.PrintWriter(file);
// Write formatted output to the file
output.print("John T Smith ");
output.println(90);
output.print("Eric K Jones ");
output.println(85);
// Close the file
output.close();
}
}
You are instanciating two times output when it is not needed.
All treatment related to output should be done in the try block so it is not executed if an error happen and the stack is redirected to exception block.
The output should be in a finally block to make sure the file is closed whatever happen.
Doing these correction, your code shoud look like this :
import java.io.*;
public class WriteData {
public static void main(String[] args) {
File file = null;
PrintWriter output = null;
try
{
file = new File("scores.txt");
output = new PrintWriter(file);
output.print("John T Smith ");
output.println(90);
output.print("Eric K Jones ");
output.println(85);
} catch (FileNotFoundException ex) {
ex.printStackTrace();
}
finally
{
//The output not be instanciated if scores.txt was not found.
if(output != null)
output.close();
}
}
}
In my opinion, this is the best way to handle your case.
try {
output = new java.io.PrintWriter(file); // output is not defined yet
} catch (FileNotFoundException ex) {
ex.printStackTrace();
}
// Create a file
// This one will throw the FileNotFoundException
java.io.PrintWriter output = new java.io.PrintWriter(file);
You can modify it like this
try {
java.io.PrintWriter output = new java.io.PrintWriter(file);
//rest of the code
} catch (FileNotFoundException ex) {
ex.printStackTrace();
}
For your error:
Remove the catch block for IoException from jean-François Savard's solution.
FileNotFoundException is a checked exception thrown by PrintWriter(). As a practice only catch the exceptions declared in API signature.
(In fact keeping any one block should work, as FileNotFoundException extends IOException )

Categories