I created a file named 'test.txt' and then took input from the user to write the input to the file. Everything runs fine. The program doesn't show any error at all. The file is created and the program takes input from the user but when I checked the content of the file, it was empty. Can anyone figure out what is wrong with my code? The code is as follows.
package InputOutput;
import java.io.*;
public class CharacterFileReaderAndFileWriter{
private BufferedReader br = null;
private BufferedWriter bw = null;
private PrintWriter pw = new PrintWriter(System.out, true);
public File createFile() throws IOException{
File f = new File("test.txt");
return f;
}
public void writeToFile() throws IOException{
try{
bw = new BufferedWriter(new FileWriter(createFile()));
}
catch(FileNotFoundException ex){
ex.printStackTrace();
}
//take input from the console (user)
br = new BufferedReader(new InputStreamReader(System.in));
String s;
pw.println("Please enter something");
pw.println("To stop the program, enter 'stop'");
do{
s = br.readLine();
if(s.compareTo("stop")==0)
break;
s+= "\r\n";//adding an new line to the string s
bw.write(s);
}
while(s.compareTo("stop")!=0);
br.close();
bw.close();
}
public static void main(String[] args) throws IOException{
CharacterFileReaderAndFileWriter cfr = new CharacterFileReaderAndFileWriter();
cfr.writeToFile();
}
}
Most example programs show that you have to call.flush() on your BufferedWriter before the .close(). This should not be required, .close() should call .flush() automatically, but it doesn't hurt. Also you should call all the Stream/Writer objects .close() methods in reverse order as well, again correctly written classes should call .close() on all the object they wrap, but it doesn't hurt to do it anyway.
Other things that might catch you out later:
if(s.compareTo("stop")==0)
should be
if ("stop".equalsIgnoreCase(s))
it is more efficient, eliminates the possibility of a NullPointerException on s, handles any case of stop and most importantly more idiomatic Java than using .compareTo()
s+= "\r\n";//adding an new line to the string s
bw.write(s);
should be
bw.write(System.getProperty("line.separator"));
bw.write(s);
The s+= creates intermediate objects and garbage that needs to be collected. Hard coding line endings is bad as well.
You need close the outputstream.
file.close();
Related
I have a simple Properties exercise
1. Read the time of program run from a configuration document ProgramRunCounter.ini
2. Each time the program run, add one more time
3. Modify the information in document
Here is the code:
class ProgramRunCounter {
public static void counter() throws IOException{
Properties prop = new Properties();
File f = new File("ProgramRunCounter.ini");
BufferedReader br;
BufferedWriter bw;
String key = "times";
String value;
int counter;
if (!f.exists()) {
f.createNewFile();
System.out.println("File created");
}
//Problem is here
br = new BufferedReader(new FileReader(f));
prop.load(br);
value = prop.getProperty(key);
bw = new BufferedWriter(new FileWriter(f));
if (value != null) {
counter = Integer.parseInt(value);
System.out.println("This program has run " + counter + " times");
counter++;
value = String.valueOf(counter);
prop.setProperty(key, value);
prop.store(bw, "One more time run!");
} else {
prop.setProperty(key, "1");
prop.store(bw, "First time run!");
}
br.close();
bw.close();
}
}
public class PropertiesDemo {
public static void main(String[] args) {
try {
ProgramRunCounter.counter();
} catch (IOException e) {
throw new RuntimeException(e.toString());
}
}
}
It works well, but problem is if i change the order of the codes like this, it can't work anymore
br = new BufferedReader(new FileReader(f));
bw = new BufferedWriter(new FileWriter(f));
prop.load(br);
value = prop.getProperty(key);
So why?
It doesn't allow insert bw = new BufferedWriter(new FileWriter(f)); between br = new BufferedReader(new FileReader(f)); and prop.load(br);?
What is the principle?
The devil is in the details. First let me just say, that you may want to just use the "new" (not soo new anymore) IO file API (i.e. Files.newBufferedReader / Files.newBufferedWriter(f.toPath()), ...). Not a must, but it makes things easier.
If you look at the javadoc of newBufferedWriter you see the following:
Opens or creates a file for writing, returning a BufferedWriter that may be used to write text to the file in an efficient manner. The options parameter specifies how the the file is created or opened. If no options are present then this method works as if the CREATE, TRUNCATE_EXISTING, and WRITE options are present. In other words, it opens the file for writing, creating the file if it doesn't exist, or initially truncating an existing regular-file to a size of 0 if it exists.
That efficiency is probably the reason why you do not see any content anymore while you are reading the file (here I assume the same efficiency is also applied under the hood, if you just use your own instantation of BufferedWriter with FileWriter which uses a FileOutputStream with append=false. If you follow all the calls you end up in a native method, so unfortunately I can't say for sure).
Now if you use Files.newBufferedWriter and you just alter the OpenOption to say SYNC or something other then TRUNCATE_EXISTING, the reader is able to load the properties again regardless of which initialization comes first, e.g.
br = Files.newBufferedReader(f.toPath());
bw = Files.newBufferedWriter(f.toPath(), StandardOpenOption.SYNC);
I'm trying to implement a method to write an array of Song() objects to a file for an assignment. I've become fairly lost on how to achieve this. I want to be able to call the function in the main method but it doesn't appear to do anything. At this stage it is a test where I want it to print on the command line upon running main().
Here's my code:
public static void main (String[] args)
{ //run the main program.
Interface songUI = new Interface();
songUI.run();
try{
PrintWriter outputTest = null;
outputTest = write("testfile");
read();
}
catch(IOException e){
System.out.println("Caught!");
}
}
public static PrintWriter write (String fileName) throws IOException{
Scanner console = new Scanner(System.in);
PrintWriter outFile = new PrintWriter(fileName);
outFile.println ("Random numbers");
for(int i=0; i<10; i++)
{
outFile.println ((int)( 1 + Math.random()*10) + " ");
}
outFile.close();
return outFile;
}
I also have a method for reading from the file i'm trying to get working here:
public static void read() throws IOException{
String fileName = "test1";
System.out.println ("The file " + fileName + "\ncontains the following lines:\n");
Scanner inputStream = new Scanner (new File (fileName));
while (inputStream.hasNextLine ())
{
String line = inputStream.nextLine ();
System.out.println (line);
}
inputStream.close ();
}
As you can tell i'm confused, and any help would be amazing. Thank you.
You are writing to testfile but trying to read from test1.
The code is poorly organized.
a method called write() shouldn't do anything else, and it should certainly not do input
returning a closed PrintWriter is completely pointless.
the write() method catches IOException internally, which makes it impossible for the caller to know about failure. Have it throw IOException instead, like the read() method does, and let the caller deal with it.
I am not being able to print all the output in file.BufferedWriter is not working well.What is my mistake to save the output of the program in file.
public class delete {
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
int alphabet=0;
char ch;
int n=0;
String line;
BufferedReader br = new BufferedReader(new FileReader("InputFileLocation"));
line= br.readLine();
while ((line = br.readLine()) != null) {
for(int i=0;i<line.length();i++){
ch=line.charAt(i);
if(ch=='a')
alphabet ++;
}
BufferedWriter bw = new BufferedWriter(new FileWriter("OutputFileLocation"));
n++;
System.out.println("case#"+n+":"+alphabet);
bw.write(String.valueOf(alphabet));
bw.close();
alphabet=0;
}
br.close();
}
}
Without running this I notice that you discard the first line by retrieving it, then retrieving another line in the first run of your condition.
Also, if you are writing every line to the output file then you probably want to move your initialization of bw outside your while loop. At the very least you want to use the FileWriter(String, boolean) constructor instead of creating a new file.
Dont create new BufferedWriter in the loop, thats a bad design.
you could try putting bw.flush() before closing it.
bw.close() implicitly call flush, but I had similar problem with this, I had to call flush explicitly to work.
I'm trying to copy a file to another file deleting a part of the string like this:
File 1:
Name = David
Age = 21
M/F = M
To file 2:
David
21
M
But the file 1 have 963 lines and its copying only 524 lines.
Is there a limit that java will write (or read) from a file?
What i did to copy it, is it bad?
package replace.strings;
import java.io.*;
import java.util.Scanner;
public class ReplaceStrings {
public static void main(String[] args){
ReplaceStrings rs = new ReplaceStrings();
try{
BufferedWriter bw = new BufferedWriter(new FileWriter(new File("C:/tarducciones/traducciones.txt"), true));
Scanner sc = new Scanner(new File("C:/tarducciones/texto.txt"));
while(sc.hasNext()){
String line = sc.nextLine();
line = rs.replace(line);
bw.write(line);
bw.newLine();
}
bw.close();
} catch(IOException ioe){
System.out.println(ioe);
}
}
public String replace(String a){
int startIndex = a.indexOf("=");
if (startIndex>0){
String toBeReplaced = a.substring(0, startIndex+1);
String resultado = a.replace(toBeReplaced, "");
return resultado;}
else return a;
}
}
EDIT: I put the bw outside the loop and still dont work.
EDIT2: Changed like you suggested, but still didnt work and no one exception is catched.
EDIT3: I deleted the first 524 data lines to see if the problem is the data inside the file, and it didnt copy any line. Can it be a problem of the data??? It's only lines in a txt
Modify your writing code, like:
BufferedWriter bw = new BufferedWriter(new FileWriter(new File("C:/tarducciones/traducciones.txt"), true));
while(sc.hasNext()){
String line = sc.nextLine();
// Avoiding creation of new String object.
bw.write(rs.replace(line));
bw.newLine();
}
bw.close();
This should work
package replace.strings;
import java.io.*;
import java.util.Scanner;
public class ReplaceStrings {
public static void main(String[] args) throws FileNotFoundException, IOException {
ReplaceStrings rs = new ReplaceStrings();
BufferedWriter bw = new BufferedWriter(new FileWriter(new File("C:/tarducciones/traducciones.txt"), true));
Scanner sc = new Scanner(new File("C:/tarducciones/texto.txt"));
while(sc.hasNext()){
String line = sc.nextLine();
String nueva = rs.replace(line);
bw.write(nueva);
bw.newLine();
}
bw.close();
}
public String replace(String a){
String str = a;
int startIndex = a.indexOf("=");
if (startIndex>0){
String toBeReplaced = str.substring(0, startIndex+1);
String resultado = str.replace(toBeReplaced, "");
return resultado;
}
else return str;
}
}
To write content to file, you should close BufferedWriter outside of while loop as other answer stated. But, I will recommend to use Java-8. Using Java-8 you can do it more easily using List#replaceAll method. Have a look at following code.
BufferedReader br = new BufferedReader(new FileReader("input.txt"));
File output=new File("output.txt");
Stream<String> lines=br.lines();
List<String> lineList=lines.collect(Collectors.toList());
lineList.replaceAll(s->s.substring(s.indexOf('=')+1));
PrintWriter pw=new PrintWriter(output);
lineList.forEach(s-> pw.write(s+"\n"));
pw.close();
Few little tweaks:
a) don't close and open writer bw inside the loop - it is inefficient to close/open it on each iteration (time consuming).
b) you don't want to work on temporary String here: String str = a; working on original will be more efficient and correct.
c) similar here: String nueva = rs.replace(line); you don't need new String. Assign result to old line.
Regarding why some lines are missing - check if you programs returns with exception (or catch it, don't throw, so it is easier to see). I can't see the reason now.
I have tried to write the console output to a txt file using this code suggestion (http://www.daniweb.com/forums/thread23883.html#) however I was not successful. What's wrong?
try {
//create a buffered reader that connects to the console, we use it so we can read lines
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
//read a line from the console
String lineFromInput = in.readLine();
//create an print writer for writing to a file
PrintWriter out = new PrintWriter(new FileWriter("output.txt"));
//output to the file a line
out.println(lineFromInput);
//close the file (VERY IMPORTANT!)
out.close();
}
catch(IOException e1) {
System.out.println("Error during reading/writing");
}
You need to do something like this:
PrintStream out = new PrintStream(new FileOutputStream("output.txt"));
System.setOut(out);
The second statement is the key. It changes the value of the supposedly "final" System.out attribute to be the supplied PrintStream value.
There are analogous methods (setIn and setErr) for changing the standard input and error streams; refer to the java.lang.System javadocs for details.
A more general version of the above is this:
PrintStream out = new PrintStream(
new FileOutputStream("output.txt", append), autoFlush);
System.setOut(out);
If append is true, the stream will append to an existing file instead of truncating it. If autoflush is true, the output buffer will be flushed whenever a byte array is written, one of the println methods is called, or a \n is written.
I'd just like to add that it is usually a better idea to use a logging subsystem like Log4j, Logback or the standard Java java.util.logging subsystem. These offer fine-grained logging control via runtime configuration files, support for rolling log files, feeds to system logging, and so on.
Alternatively, if you are not "logging" then consider the following:
With typical shells, you can redirecting standard output (or standard error) to a file on the command line; e.g.
$ java MyApp > output.txt
For more information, refer to a shell tutorial or manual entry.
You could change your application to use an out stream passed as a method parameter or via a singleton or dependency injection rather than writing to System.out.
Changing System.out may cause nasty surprises for other code in your JVM that is not expecting this to happen. (A properly designed Java library will avoid depending on System.out and System.err, but you could be unlucky.)
There is no need to write any code, just in cmd
on the console you can write:
javac myFile.java
java ClassName > a.txt
The output data is stored in the a.txt file.
to preserve the console output, that is, write to a file and also have it displayed on the console, you could use a class like:
public class TeePrintStream extends PrintStream {
private final PrintStream second;
public TeePrintStream(OutputStream main, PrintStream second) {
super(main);
this.second = second;
}
/**
* Closes the main stream.
* The second stream is just flushed but <b>not</b> closed.
* #see java.io.PrintStream#close()
*/
#Override
public void close() {
// just for documentation
super.close();
}
#Override
public void flush() {
super.flush();
second.flush();
}
#Override
public void write(byte[] buf, int off, int len) {
super.write(buf, off, len);
second.write(buf, off, len);
}
#Override
public void write(int b) {
super.write(b);
second.write(b);
}
#Override
public void write(byte[] b) throws IOException {
super.write(b);
second.write(b);
}
}
and used as in:
FileOutputStream file = new FileOutputStream("test.txt");
TeePrintStream tee = new TeePrintStream(file, System.out);
System.setOut(tee);
(just an idea, not complete)
Create the following method:
public class Logger {
public static void log(String message) {
PrintWriter out = new PrintWriter(new FileWriter("output.txt", true), true);
out.write(message);
out.close();
}
}
(I haven't included the proper IO handling in the above class, and it won't compile - do it yourself. Also consider configuring the file name. Note the "true" argument. This means the file will not be re-created each time you call the method)
Then instead of System.out.println(str) call Logger.log(str)
This manual approach is not preferable. Use a logging framework - slf4j, log4j, commons-logging, and many more
In addition to the several programatic approaches discussed, another option is to redirect standard output from the shell. Here are several Unix and DOS examples.
You can use System.setOut() at the start of your program to redirect all output via System.out to your own PrintStream.
This is my idea of what you are trying to do and it works fine:
public static void main(String[] args) throws IOException{
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter out = new BufferedWriter(new FileWriter("c://output.txt"));
try {
String inputLine = null;
do {
inputLine=in.readLine();
out.write(inputLine);
out.newLine();
} while (!inputLine.equalsIgnoreCase("eof"));
System.out.print("Write Successful");
} catch(IOException e1) {
System.out.println("Error during reading/writing");
} finally {
out.close();
in.close();
}
}
The easiest way to write console output to text file is
//create a file first
PrintWriter outputfile = new PrintWriter(filename);
//replace your System.out.print("your output");
outputfile.print("your output");
outputfile.close();
To write console output to a txt file
public static void main(String[] args) {
int i;
List<String> ls = new ArrayList<String>();
for (i = 1; i <= 100; i++) {
String str = null;
str = +i + ":- HOW TO WRITE A CONSOLE OUTPUT IN A TEXT FILE";
ls.add(str);
}
String listString = "";
for (String s : ls) {
listString += s + "\n";
}
FileWriter writer = null;
try {
writer = new FileWriter("final.txt");
writer.write(listString);
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
If you want to generate the PDF rather then the text file, you use the dependency given below:
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itextpdf</artifactId>
<version>5.0.6</version>
</dependency>
To generate a PDF, use this code:
public static void main(String[] args) {
int i;
List<String> ls = new ArrayList<String>();
for (i = 1; i <= 100; i++) {
String str = null;
str = +i + ":- HOW TO WRITE A CONSOLE OUTPUT IN A PDF";
ls.add(str);
}
String listString = "";
for (String s : ls) {
listString += s + "\n";
}
Document document = new Document();
try {
PdfWriter writer1 = PdfWriter
.getInstance(
document,
new FileOutputStream(
"final_pdf.pdf"));
document.open();
document.add(new Paragraph(listString));
document.close();
writer1.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (DocumentException e) {
e.printStackTrace();
}
}
PrintWriter out = null;
try {
out = new PrintWriter(new FileWriter("C:\\testing.txt"));
} catch (IOException e) {
e.printStackTrace();
}
out.println("output");
out.close();
I am using absolute path for the FileWriter. It is working for me like a charm. Also Make sure the file is present in the location. Else It will throw a FileNotFoundException. This method does not create a new file in the target location if the file is not found.
In netbeans, you can right click the mouse and then save as a .txt file. Then, based on the created .txt file, you can convert to the file in any format you want to get.