I am trying to write to a file, which another process can read. I am using the Printwiter to write to a file. But it doesnt write to the file as long as i dont terminate the program. I have eanbles the autflush on, and even explicitly flusing. The code is below -
import java.io.FileWriter;
import java.io.PrintWriter;
public class ReadFile {
public static void main(String[] args) {
try {
// Create a print writer
FileWriter fw = new FileWriter("D:\\SpringProjects\\RescilienceModel\\natural_resource.txt");
//BufferedWriter bw = new BufferedWriter(fw);
PrintWriter pw = new PrintWriter(fw, true);
// Experiment with some methods
while(true)
{
pw.println(99);
pw.flush();
}
} catch (Exception e) {
System.out.println("Exception: " + e);
}
}
}
Two issues.
Check that while(true) loop, or it won't end.
close() your handle, or it won't release resources.
Related
I have this code:
try {
File file = new File(something+counter+".txt");
counter++;
if (!file.exists()) {
file.createNewFile();
}
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
bw.write(content);
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
I need to make it like this: When they press enter, new file will be created in defined location (I made JTextField for this), but when they press it again, the file OVERWRITES. That's the problem. I need them to press enter - create new file: sample1.txt, press enter again, create new file: sample2.txt
OK by looking at your code now, it looks fine, but you probably declared the counter variable within the method. If so, it will be 'reset' to whatever you set it to every time the method is called.
EDIT:
This should work.
import java.io.*;
public class Example {
public static void main(String args[]) {
Example ex = new Example();
ex.writeFile();
ex.writeFile();
}
private void writeFile() {
try {
File file = new File("file" + counter + ".txt");
counter++;
System.out.println("Writing to " + file.toString());
if (!file.exists()) {
file.createNewFile();
}
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
bw.write("content");
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
private int counter = 0;
}
I get
Writing to file0.txt
Writing to file1.txt
as output and both files have the string 'content' written in them.
EDIT2:
Call writefile whenever the user presses enter.
I'm just want a program to register a user and then create a txt file to store there the information. I know it has to be with createNewFile method but I do not know how to use it. I'd try this in my code:
import java.util.*;
public class File{
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
byte option=0;
do{
System.out.println("\nMENU:\n");
System.out.println("0.-EXIT");
System.out.println("1.-REGISTER USER");
System.out.println("\nPLEASE ENTER YOUR CHOICE:");
option = sc.nextByte();
}while(option!=0);
}//main
}//File
You can use a File object to create a new File an example is:
File createFile = new File("C:\\Users\\youruser\\desktop\\mynewfile.txt");
createFile.createNewFile();
If you want to read and write to the file you could use a PrintWriter or some other writing mechanism:
PrintWriter pw = new PrintWriter(createFile);
pw.write("File Contents");
//when you are done flush and close the pw
pw.flush();
pw.close();
If you need to append to the file you can do this:
PrintWriter pw = new PrintWriter(new FileOutputStream(createFile, true)); //true means append here
pw.append("File Contents");
//when you are done flush and close the pw
pw.flush();
pw.close();
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
public class WriteToFileExample {
public static void main(String[] args) {
try {
String content = "This is the content to write into file";
// File file = new File("/users/your_user_name/filename.txt");// unix case
File file = new File("c:\\filename.txt"); //windows case
// if file doesnt exists, then create it
if (!file.exists()) {
file.createNewFile();
}
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
bw.write(content);
bw.close();
System.out.println("Done");
} catch (IOException e) {
e.printStackTrace();
}
}
}
Source: http://www.mkyong.com/java/how-to-write-to-file-in-java-bufferedwriter-example/
Ok so once you have the input from the user this is what you would use to write the username and password to a text file
try {
File file = new File("userInfo.txt");
BufferedWriter output = new BufferedWriter(new FileWriter(file, true));
//set to true so you can add multiple users(it will append (false will create a new one everytime))
output.write(username + "," + password);
output.close();
} catch (IOException e) {
e.printStackTrace();
}
EDIT***
You can put all this in a method and call it every time you want to add the user
public void addUser(String username, String password){
//my code from above ^^
}
I asked a similar question before regarding I/O using Java.
I'm trying to copy a list of strings into another file.
package file;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class File {
public static void main(String[] args) {
FileWrite fW = new FileWrite();
try (BufferedReader br = new BufferedReader(new FileReader("B:\\inLarge.dat")))
{
String stCurrent;
while ((stCurrent = br.readLine()) != null) {
System.out.println(stCurrent);
fW.serializeAddress(stCurrent, stCurrent);
}
} catch (IOException e) {
e.printStackTrace();
}
//fW.serializeAddress("Boston", "Canada");
}
}
And
package file;
import java.io.BufferedWriter;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.ObjectOutputStream;
import java.io.PrintStream;
import java.io.Serializable;
import java.io.File;
import java.io.IOException;
public class FileWrite {
public void serializeAddress(String city, String country){
try
{
File file = new File("B:\\outLarge.txt");
if (!file.exists())
{
file.createNewFile();
}
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
bw.write(city + " " + country);
bw.close();
System.out.println("Done");
}
catch(Exception ex)
{
ex.printStackTrace();
}
}
}
But the ending output file has only one result, how do I make it copy everything?
I am thinking buffered-writer somehow needs to be in the loop to write new ones on top of existing ones? But not sure how to implement that.
Thanks a lot.
You are overwriting the file contents every time you call your serialize method, because you didn't open the file in append mode. To prevent overwriting, open the file in append mode:
FileWriter fw = new FileWriter(file.getAbsoluteFile(), true);
However, this is one case where the solution is probably over-engineered. For efficiency you really should be opening your file just once. Here's an example:
public static void main(final String[] args) {
try {
final BufferedReader reader = new BufferedReader(new FileReader("infile.txt"));
final PrintWriter writer = new PrintWriter(new File("outfile.txt"));
String inputLine;
while((inputLine = reader.readLine()) != null) {
writer.println(inputLine);
}
reader.close();
writer.close();
} catch(final Exception e) {
e.printStackTrace();
}
}
You're overwriting the existing file every time you open it. Instead append to it.
Change
FileWriter fw = new FileWriter(file.getAbsoluteFile());
to
FileWriter fw = new FileWriter(file.getAbsoluteFile(), true);
I just started doing file I/O andim using an example from Murach's Se 6.
Here is my code. Am i missing something. I know the code further on has more but as this is an example this should work right?
//Import import java.io.*; for use with the File I/O Methods.
import java.io.*;
public class MainApp
{
public static void main(String[] args)
{
//Create a file object.
File productFile = new File("product.txt");
//Open a buffered output stream to allow write to file operations.
PrintWriter out = new PrintWriter(
new BufferedWriter(
new FileWriter(productFile)));
out.println("java\tMurach's Beginning Java 2\t$49.99");
out.close();
BufferedReader in = new BufferedReader(
new FileReader(productFile));
String line = in.readLine();
System.out.println(line);
out.close();
}
}
//Answer
by adding a throws exception to the end of where i initialised the main this code works. Even the txt file products.txt is in the class folder as expected.
//Import import java.io.*; for use with the File I/O Methods.
import java.io.*;
public class MainApp
{
public static void main(String[] args) throws Exception
{
//Create a file object.
File productFile = new File("product.txt");
//Open a buffered output stream to allow write to file operations.
PrintWriter out = new PrintWriter(
new BufferedWriter(
new FileWriter(productFile)));
out.println("java\tMurach's Beginning Java 2\t$49.99");
out.close();
BufferedReader in = new BufferedReader(
new FileReader(productFile));
String line = in.readLine();
System.out.println(line);
out.close();
}
}
The problem is that a number of the calls to the java.io package throw exceptions.
easy fix: add the following to your method signature
public static void main(String[] args) throws IOException
almost as easy fix: add try/catch/finally blocks.
public static void main(String[] args)
{
//Create a file object.
File productFile = new File("product.txt");
//Open a buffered output stream to allow write to file operations.
PrintWriter out = null;
try {
out = new PrintWriter(
new BufferedWriter(
new FileWriter(productFile)));
out.println("java\tMurach's Beginning Java 2\t$49.99");
}
catch(IOException ex) {
// todo exception handling
System.out.println("ERROR! " + ex);
}
finally {
out.close();
}
BufferedReader in = null;
try {
in = new BufferedReader(
new FileReader(productFile));
String line = in.readLine();
System.out.println(line);
}
catch (IOException ex) {
// todo more exception handling
System.out.println("ERROR! " + ex);
}
finally {
in.close();
}
}
edit: you know you are trying to call out.close() twice? The second should be a call to in.close()
CODE
import java.io.*;
class tester {
public static void main(String args[]) {
try {
FileReader reader = new FileReader(new File("d:\\UnderTest\\check123.txt"));
FileWriter writer = new FileWriter(new File("d:\\UnderTest\\check123.txt"));
BufferedReader br = new BufferedReader(reader);
String s;
while( (s=br.readLine()) != null ) {
System.out.println(s);
}
writer.write("Shadow Shadow");
} catch(Exception exc) {
System.out.println(exc);
}
}
}
This code writes nothing and reads nothing when i run it. Where is the bug in this program ?
Are you sure that when you read for first time then content is there in the text file ?
You need to close Reader and Writer in finally block (missing currently in your code) of your try-catch block. closing the stream flushes out content automatically.
Make sure you close the reader and the writer. After using the writer you will need to flush the contents or close the writer (which does the same thing). I tested this and it works.
import java.io.*;
class tester {
public static void main(String args[]) {
try {
FileReader reader = new FileReader(new File("c:\\check123.txt"));
FileWriter writer = new FileWriter(new File("c:\\check123.txt"));
BufferedReader br = new BufferedReader(reader);
writer.write("Shadow Shadow");
writer.close();
String s;
while( (s=br.readLine()) != null ) {
System.out.println(s);
}
reader.close();
} catch(Exception exc) {
System.out.println(exc);
}
}
}