Append text to file and print it's contents to console simultaneously? - java

I've spent over an hour on this, and i just can't get any text to show up in the .txt file. What am i doing wrong?
import java.util.*;
import java.io.*;
public class writer {
public static void main(String[] args) {
try {
File txt = new File("myTextFile.txt");
FileWriter fw = null;
fw = new FileWriter(txt);
BufferedWriter edit = null;
edit = new BufferedWriter(fw);
String s = "more text", line = null;
edit.write(s);
Scanner sc = new Scanner(txt);
while (sc.hasNextLine()) {
String i = sc.nextLine();
System.out.println(i);
}
sc.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Edit: Added a .write, but it's still not working

You never close the BufferedWriter instance and you never flush it either. So you never leave a change the buffer of the stream to be effectively written in the physical file.
Actually you read the file from the same source that you use just before to write in. So you have to explicitly flush the buffer of BufferedWriter before reading the content with the Scanner :
BufferedWriter edit = new BufferedWriter(fw);
String s = "more text", line = null;
edit.write(s);
edit.flush(); // modification here
Scanner sc = new Scanner(txt);

Related

Java IO: Using scanner and printWriter to copy the contents of a text file and put them in another text file

Alright so I have a very small program I'm working on designed to take the contents of a text file, test.txt, and put them in another empty file testCopied.txt . The trick is that I want to use Scanner and printWriter as I am trying to understand these a bit better.
Here is what my code looks like:
import java.io.*;
import java.util.*;
public class CopyA
{
public static void main(String [] args)
{
String Input_filename = args[0];
String Output_filename = args[1];
char r = args[2].charAt(0);
try
{
Scanner sc = new Scanner(new File(Input_filename));
FileWriter fw = new FileWriter(Output_filename);
PrintWriter printer = new PrintWriter(fw);
while(sc.hasNextLine())
{
String s = sc.nextLine();
printer.write(s);
}
sc.close();
}
catch(IOException ioe)
{
System.out.println(ioe);
}
}
}
This compiles, but when I look at testCopied.txt it is still blank, and hasn't had test.txt's content transferred to it. What am I doing wrong? Java IO is pretty confusing to me, so I'm trying to get a better grasp on it. Any help is really appreciated!
You have missed out flush() and close() for the PrintWriter object which you need to add
and then use the line separator using System.getProperty("line.separator") while writing each line into second file.
You can refer the below code:
PrintWriter printer = null;
Scanner sc = null;
try
{
String lineSeparator = System.getProperty("line.separator");
sc = new Scanner(new File(Input_filename));
FileWriter fw = new FileWriter(Output_filename);
printer = new PrintWriter(fw);
while(sc.hasNextLine())
{
String s = sc.nextLine()+lineSeparator; //Add line separator
printer.write(s);
}
}
catch(IOException ioe)
{
System.out.println(ioe);
} finally {
if(sc != null) {
sc.close();
}
if(printer != null) {
printer.flush();
printer.close();
}
}
Also, ensure that you are always closing resources in the finally block (which you have missed out for Scanner object in your code).

How to write to file

I tried to make a console app that creates a file and writes text to it. What did I do wrong here?
package Writer;
import java.util.*;
import java.io.*;
public class main {
public static void main(String args[]) {
System.out.println("What would you like your SimpleText file name to be?");
Scanner uInputName = new Scanner(System.in);
String fileName = uInputName.nextLine();
File file = new File(fileName);
FileWriter fw = FileWriter;
BufferedWriter Text = new BufferedWriter(fw);
{
System.out.println("What would you like to write in: " + fileName);
Scanner uInputText = new Scanner(System.in);
String fileText = uInputText.nextLine();
fw.write(fileText);
Text.newLine();
}
System.out.println("Okay. File saved.");
}
This is totally illegal
FileWriter fw = FileWriter;
You probably want this
BufferedWriter Text = new BufferedWriter(new FileWriter(file));
You have an unnecessary code block
{
}
Your code is going to throw an IOExcpeption, so you have two options. Either
public static void main(String[] args) throws IOException {
}
Or
try {
BufferedWriter Text = new BufferedWriter(new FileWriter(file));
....
Text.write(inputText);
Text.close();
} catch (IOException ex) {
ex.printStackTrace();
}
First, let us begin with FileWriter fw.
fw should be a FileWriter object and so, you need to create a FileWriter object.
FileWriter fw = new FileWriter(file);
Now, notice that you may want to be more specific so it's worth checking the different constructors in the FileWriter API
Also, the writing won't THROW and exception, it MIGHT THROW an exception (saying that it will throw an exception is saying that your code will always fail and in that case, exception handling is "patching" it.
So I would recommend adding a catch clause. However, remember that YOU must ALWAYS close the writers yourself (Java does not do that unless specified otherwise) and so, you need to either try with resource
try (FileWriter fw = new FileWriter(file);
BufferedWriter bw = new BufferedWriter(fw)){
....
writer.write(inputText);
} catch (IOException ex) {
ex.printStackTrace();
}
or, add a finally clause
FileWriter fw = new FileWriter(file);
BufferedWriter writer = new BufferedWriter(fw);
try {
....
writer.write(inputText);
} catch (IOException ex) {
ex.printStackTrace();
} finally{
writer.close();
fw.close();
}
Because the garbage collector does not close streams and if the exception is thrown inside the try then it will not reach the close() command but instead go to catch (and then finally) without closing the stream.
As others have said. it is difficult to know all the things that are wrong without knowing what exactly you are trying to accomplish.
And again, as PopoFibo mentioned, the thing that probably stands out most and seems to be syntactically incorrect is:
FileWriter fw = FileWriter;
So instead of listing what might be wrong, here is an example that might help you.
In first line you you enter in console you specify the file name - like you seem to want to do.
Each subsequent line you input into console is written to that file. Entering empty line will terminate the input.
public class Program {
public static void main(String[] args) {
System.out.println("Enter file name:");
Scanner input = new Scanner(System.in);
String fileName = null;
while (fileName == null) {
if (input.hasNextLine()) {
fileName = input.nextLine();
}
}
try {
FileWriter fw = new FileWriter(fileName);
String newLine = System.getProperty("line.separator");
System.out.println("Enter lines (enter empty line to terminate):");
String line = null;
while (true) {
if (input.hasNextLine()) {
line = input.nextLine();
if (isTerminatingEntry(line)) {
break;
}
fw.write(line + newLine);
}
}
fw.close();
} catch (IOException e) {
e.printStackTrace();
}
input.close();
}
private static boolean isTerminatingEntry(String line) {
// add some condition that will cause you to stop reading input
// in this example, empty line will terminate the input
return line.length() == 0;
}
}

Modify the content of a file using Java

I want to delete some content of file using java program as below. Is this the write method to replace in the same file or it should be copied to the another file.
But its deleting the all content of the file.
class FileReplace
{
ArrayList<String> lines = new ArrayList<String>();
String line = null;
public void doIt()
{
try
{
File f1 = new File("d:/new folder/t1.htm");
FileReader fr = new FileReader(f1);
BufferedReader br = new BufferedReader(fr);
while (line = br.readLine() != null)
{
if (line.contains("java"))
line = line.replace("java", " ");
lines.add(line);
}
FileWriter fw = new FileWriter(f1);
BufferedWriter out = new BufferedWriter(fw);
out.write(lines.toString());
}
catch (Exception ex)
{
ex.printStackTrace();
}
}
public statc void main(String args[])
{
FileReplace fr = new FileReplace();
fr.doIt();
}
}
I would start with closing reader, and flushing writer:
public class FileReplace {
List<String> lines = new ArrayList<String>();
String line = null;
public void doIt() {
try {
File f1 = new File("d:/new folder/t1.htm");
FileReader fr = new FileReader(f1);
BufferedReader br = new BufferedReader(fr);
while ((line = br.readLine()) != null) {
if (line.contains("java"))
line = line.replace("java", " ");
lines.add(line);
}
fr.close();
br.close();
FileWriter fw = new FileWriter(f1);
BufferedWriter out = new BufferedWriter(fw);
for(String s : lines)
out.write(s);
out.flush();
out.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}
public static void main(String args[]) {
FileReplace fr = new FileReplace();
fr.doIt();
}
}
The accepted answer is great. However, there is an easier way to replace content in a file using Apache's commons-io library (commons-io-2.4.jar - you can use any latest versions)
private void update() throws IOException{
File file = new File("myPath/myFile.txt");
String fileContext = FileUtils.readFileToString(file);
fileContext = fileContext.replaceAll("_PLACEHOLDER_", "VALUE-TO-BE-REPLACED");
FileUtils.write(file, fileContext);
}
Note: Thrown IOException needs to be caught and handled by the application accordingly.
Read + write to the same file simulatenously is not ok.
EDIT: to rephrase and be more correct and specific - reading and writing to the same file, in the same thread, without properly closing the reader (and flusing the writer) is not ok.
Make sure to:
close any stream when you no longer need them
In particular before reopening it for writing.
truncate the file, to make sure it shrinks if you write less than it had.
then write the output
write individual lines, don't rely on toString.
flush and close when you are finished writing!
If you use buffered IO, you always have to ensure that the buffer is flushed at the end, or you might lose data!
I can see three problems.
First you are writing to out which I assume is System.out, not an output stream to the file.
Second, if you do write to an output stream to the file, you need to close it.
Third, the toString() method on an ArrayList isn't going to write the file like you are expecting. Loop over the list and write each String one at a time. Ask yourself whether you need to write newline characters as well.
The accepted answer is slightly wrong. Here's the correct code.
public class FileReplace {
List<String> lines = new ArrayList<String>();
String line = null;
public void doIt() {
try {
File f1 = new File("d:/new folder/t1.htm");
FileReader fr = new FileReader(f1);
BufferedReader br = new BufferedReader(fr);
while ((line = br.readLine()) != null) {
if (line.contains("java"))
line = line.replace("java", " ");
lines.add(line);
}
fr.close();
br.close();
FileWriter fw = new FileWriter(f1);
BufferedWriter out = new BufferedWriter(fw);
for(String s : lines)
out.write(s);
out.flush();
}
out.close();
catch (Exception ex) {
ex.printStackTrace();
}
}

Java Read / Write To File - BufferedReader BufferedWriter [duplicate]

This question already has answers here:
BufferedWriter not writing everything to its output file
(8 answers)
Closed 8 years ago.
This is a code snippet but basically what I want to do is read from a file named 'listings.txt' and write to a file named 'overview.txt'. I want to take the information out of 'listings.txt' and put them into 'overview.txt' as is (I will figure out the rest later).
The file 'overview.txt' is created and appears to loop through the file 'listings.txt' and write to 'overview.txt'. However, once I open the file 'overview.txt' it is empty. Could someone go through a quick glance at my code and spot something erroneous?
package yesOverview;
import java.io.BufferedReader;
import java.io.*;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;
public class yesOverview {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String strInput = "foo.bar";
System.out.print("Please enter the listings file (the full path to the file): ");
strInput = input.next();
//This makes sure that the inputed file is listings.txt as required for KET1 task 2
while (strInput.contains("listings.txt") == false) {
System.out.print("Incorrect file. Please enter listings file(the full path to the file): ");
strInput = input.next();
}
infos(strInput);
input.close();
}
public static void infos(String strInput) {
Scanner input2 = new Scanner(System.in);
System.out.print("Please enter the overview.txt file (the full path to the file): ");
String strInput2 = "foo.bar";
strInput2 = input2.next();
//This also makes sure that the overview.txt file is provided.
while (strInput2.contains("overview.txt") == false) {
System.out.print("Incorrect file. Please enter overview file(the full path to the file): ");
strInput2 = input2.next();
}
//Creates the file f then places it in the specified directory.
File f = new File(strInput2);
try {
//Creates a printerwriter out that writes to the output file.
PrintWriter out = new PrintWriter(strInput2);
} catch (FileNotFoundException ex) {
Logger.getLogger(KETTask2Overview.class.getName()).log(Level.SEVERE, null, ex);
}
//String that holds the value of the next line.
String inputLine = "";
//Creates the Buffered file reader / writer.
try {
BufferedReader in = new BufferedReader(new FileReader(strInput));
FileWriter fstream = new FileWriter(strInput2);
BufferedWriter out = new BufferedWriter(fstream);
while (in.readLine() != null) {
out.write(in.read());
}
in.close();
} catch (IOException e) {
System.err.println("Error: " + e.getMessage());
}
}
}
Try this
Close the BufferedWriter stream (ie out.close() )
try and use nextLine() instead of next(), as next() only takes in a single word, but for a complete line use nextLine(), though this doesnt seem to be the problem here.
What i do when i have to read and write to files, i normally follow these steps
For Reading from a file
File f = new File("my.txt");
FileReader fr = new FileReader(f);
BufferedReader br = new BufferedReader(fr);
String s = null;
while ((br.readLine())!=null) {
// Do whatever u want to do with the content of the file,eg print it on console using SysOut...etc
}
br.close();
For Writing to a file:
Boolean isDone = true;
Scanner scan = new Scanner(System.in);
File f = new File("my.txt");
FileWriter fr = new FileWriter(f);
BufferedWriter br = new BufferedWriter(fr);
while (isDone) {
if (!isDone) {
br.write(new Scanner(System.in).nextLine());
}
}
public static long copy (Reader input, Writer output) throws IOException {
char[] buffer = new char[8192];
long count = 0;
int n;
while ((n = input.read( buffer )) != -1) {
output.write( buffer, 0, n );
count += n;
}
return count;
}
Usage Example:
copy( reader, new FileWriter( file ) );
You're not closing out.
The finally block for the writeList method cleans up and then closes the BufferedWriter.
finally {
if (out != null) {
System.out.println("Closing BufferedWriter");
out.close();
} else {
System.out.println("BufferedWriter not open");
}
}

write a string into file

I have the above code. What i wanna do is to write in a txt file a string.
import java.io.*;
import java.util.*;
public void writeAsfalizomenos(asfalizomenos myObj) throws IOException {
Scanner scanner = new Scanner(System.in);
System.out.print("Surname: ");
String username = scanner.nextLine();
System.out.println(username);
FileWriter outFile = new FileWriter("asdf.txt", true);
PrintWriter out1 = new PrintWriter(outFile);
out1.append(username);
out1.println();
out1.append("adfdas");
//
// Read string input for username
//
}
public static void main(String [] args) throws IOException{
asfalizomenos a = new asfalizomenos();
a.writeAsfalizomenos(a);
}
The above code creates a txt file but it doesnt write the string to it. Any idea about my bug??
You're not closing or flushing the PrinterWriter or the FileWriter. So basically it's being buffered, so nothing is being written to the file.
You should close both in finally blocks:
FileWriter outFile = new FileWriter("asdf.txt", true);
try {
PrintWriter out1 = new PrintWriter(outFile);
try {
out1.append(username);
out1.println();
out1.append("adfdas");
} finally {
out1.close();
}
} finally {
outFile.close();
}
Closing will flush automatically.
(I can't remember - it's likely that closing the PrintWriter will close the FileWriter. Personally I like to be explicit about it anyway.)
Close the PrintWriter after you're done writing to it:
out1.close();

Categories

Resources