How To Write Next Line To File - java

I have tried using writer.newLine() however it says method not found. Does anyone know how I can write a new line after each iteration?
public static void keepLetters() throws IOException {
BufferedReader sourceReader = new BufferedReader(new FileReader("input.txt"));
for (String line = sourceReader.readLine(); line != null; line = sourceReader.readLine()) {
String updatedLine = line.replaceAll("[^A-Za-z]", "");
System.out.println(updatedLine);
try (Writer writer = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream("output.txt"), "UTF-8"))) {
writer.write(updatedLine);
}
}
}
I wrote writer.nextLine() after writer.write(updatedLine);
Thank you

The correct method is newLine(), but you need to call it on a BufferedWriter, not a Writer.
Like so:
try (BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream("output.txt", true), "UTF-8"))) {
writer.write(updatedLine);
writer.newLine();
}
Note this part try (BufferedWriter writer
Update for comment
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("output.txt"), "UTF-8"));
for (int i = 0; i < linesToWrite; i++){
writer.write(updatedLine);
writer.newLine();
}
writer.close();

You can simple do
writer.write(updatedLine + "\n");
which will ensure a newline is written after every updatedLine.
EDIT:
The writer is being reinitiated to the same file output every iteration of the loop. It should be initialised once before the loop and closed later on to resolve your issue.

Related

How can I make PrintWriter NOT append to a file?

I have a server that writes to a logfile, but I do not want to append lines. I have set the flag to false, but still it seems to be appending. How can I make it REPLACE the first line everytime so my file contains one updated line everytime ?
fos = new FileOutputStream(new File(filename), false);
PrintWriter bw = new PrintWriter(new OutputStreamWriter(fos));
..
..
while(true){
line = getRandomLine();
bw.println(line);
bw.flush();
}
..
..
If I understand You correctly, you want this:
File file = new File(filename);
while (true) {
pw = new PrintWriter(file);
line = getRandomLine();
pw.println(line);
pw.flush();
pw.close();
}

How to close a file in java

This is my code :
FileWriter fw = new FileWriter(log,true);
BufferedWriter bw = new BufferedWriter(fw);
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
fw.close();
bw.close();
sw.close();
pw.close();
I want to change it to something like this :
BufferedWriter bw = new BufferedWriter(new FileWriter(log,true));
PrintWriter pw = new PrintWriter(new StringWriter());
bw.close();
pw.close();
Will this be correct, or will the missing close() calls cause problems?
To be sure the close is not forgotten you could use the try-with-resource statement
try (BufferedWriter bw = new BufferedWriter(new FileWriter(log, true));
PrintWriter pw = new PrintWriter(new StringWriter())) {
// do your processing here
} catch (IOException ex) {
// do your exception handling
}
The compiler will add for your the appropriate code for the close().
When you close a BufferedWriter Object which takes a FileWriter Object in its constructor, then implicitly the FileWriter Object is also closed.
So to answer your question, both ways are fine and the same and it don't make any problem
Previous Answer
Best practice
Since Java 7 you can let java automatically close the resources for you. Take a look at the try with resources.
try (BufferedReader br = new BufferedReader(new FileReader(path))) {
return br.readLine();
}

Modify 1 word in a line from File and the remain rest of the lines the same

This code change the modify data and it only remain the line which is modified not the rest of lines.
bw = new BufferedWriter(new FileWriter(file, true));
replacedLine = CurrentLine.replace(PASSWORD,password);
bw.write(replacedLine);
RESIDENTS_OLDDETAILS = new File(file);
RESIDENTS_OLDDETAILS.delete();
RESIDENTS_NEWDETAILS = new File(newfile);
RESIDENTS_NEWDETAILS.renameTo(file);
bw.close();
I want to change old line detail and remain the rest of the lines the same.
Example:
abc,1234,test
ddd,2345,test1
to
abc,9999,test
ddd,2345,test1
You can put all the updated lines in new variable and at the end write those new lines in new file.
StringBuilder updatedContents = new StringBuilder();
while(currentLine != null) {
updatedContents.append(currentLine.replace(PASSWORD, password));
updatedContents.append("\n");
currentLine = reader.readLine();
}
BufferedWriter writer = new BufferedWriter(new FileWriter("filename"));
writer.write(updatedContents.toString());
writer.close();
i think this will help you..

Java - how to read from file when I used PrintWriter, BufferedWriter and FileWriter to write?

I have method which writes some data to file. I use PrintWriter, BufferedWriter and FileWriter as shown below
public void writeToFile(String FileName){
PrintWriter pw = null;
try {
pw = new PrintWriter(new BufferedWriter(new FileWriter(FileName)));
for(Cars car : list){
pw.println(car.getType());
pw.println(car.getMaxSpeed());
pw.println(car.getOwner());
pw.println();
pw.flush();
}
pw.close();
}
catch(IOException ex){
System.err.println(ex);
}
}
Now how can I read this data from file? I tried to use InputStreamReader, BufferedReader and FileInputStream, but my NetBeans shows me an error message
public void readFromFile() throws IOException {
InputStreamReader fr = null;
try {
fr = new InputStreamReader(new BufferedReader(new FileInputStream(new FileReader("c:\\cars.txt"))));
System.out.println(fr.read());
} catch (Exception ex) {
System.out.println(ex.getMessage());
} finally {
fr.close();
}
}
What is wrong with this method?
BufferedReader in = new BufferedReader(new FileReader("file.in"));
BufferedWriter out = new BufferedWriter(new FileWriter("file.out"));
String line = in.readLine(); // <-- read whole line
StringTokenizer tk = new StringTokenizer(line);
int a = Integer.parseInt(tk.nextToken()); // <-- read single word on line and parse to int
out.write(""+a);
out.flush();
There are several problems in your code :
1) An InputStreamReader takes an InputStream as an argument not a Reader. See http://docs.oracle.com/javase/6/docs/api/java/io/InputStreamReader.html.
2) The FileInputStream does not accept a Reader as argument as well (it takes a File, a FileDescriptor, or a String). See : http://docs.oracle.com/javase/6/docs/api/java/io/FileInputStream.html
3) A BufferedReader reads the File line by line normally. The read() method only reads a single character.
A possible solution could be :
fr = new BufferedReader(new InputStreamReader(new FileInputStream(new File("c:\\cars.txt"))));
String line = "";
while((line = fr.readLine()) != null) {
System.out.println(line);
}
Btw : It would be easier for others to help you, if you provide the exact error-message or even better the StackTrace.
Simple error: Cannot resolve constructor 'FileInputStream(java.io.FileReader)', required constructor not exist in API.
Your original code was:
new PrintWriter(new BufferedWriter(new FileWriter(FileName)));
so for reading, you need
new PrintReader(new BufferedReader(new FileReader(FileName)));
but PrintReader is not needed (not exist), so all you need is:
new BufferedReader(new FileReader(FileName))
PrinterWriter prints formatted representations of objects to a text-output stream, but when reading text is always formatted, so PrinterReader not exist.
You are writing line by line, so also read line by line :) Example:
public void readFromFile() throws IOException {
BufferedReader bufferedReader = null;
try {
String sCurrentLine;
bufferedReader = new BufferedReader(new FileReader("c:\\cars.txt"));
while ((sCurrentLine = bufferedReader.readLine()) != null) {
System.out.println(sCurrentLine);
}
} catch (Exception ex) {
System.out.println(ex.getMessage());
} finally {
bufferedReader.close();
}
}
or better (JDK7)
void readFromFile() throws IOException {
Path path = Paths.get("c:\\cars.txt");
try (BufferedReader reader = Files.newBufferedReader(path, Charset.defaultCharset())){
String line = null;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
}
}

Java read in single file and write out multiple files

I want to write a simple java program to read in a text file and then write out a new file whenever a blank line is detected. I have seen examples for reading in files but I don't know how to detect the blank line and output multiple text files.
fileIn.txt:
line1
line2
line3
fileOut1.txt:
line1
line2
fileOut2.txt:
line3
Just in case your file has special characters, maybe you should specify the encoding.
FileInputStream inputStream = new FileInputStream(new File("fileIn.txt"));
InputStreamReader streamReader = new InputStreamReader(inputStream, "UTF-8");
BufferedReader reader = new BufferedReader(streamReader);
int n = 0;
PrintWriter out = new PrintWriter("fileOut" + ++n + ".txt", "UTF-8");
for (String line;(line = reader.readLine()) != null;) {
if (line.trim().isEmpty()) {
out.flush();
out.close();
out = new PrintWriter("file" + ++n + ".txt", "UTF-8");
} else {
out.println(line);
}
}
out.flush();
out.close();
reader.close();
streamReader.close();
inputStream.close();
I don't know how to detect the blank line..
if (line.trim().length==0) { // perform 'new File' behavior
.. and output multiple text files.
Do what is done for a single file, in a loop.
You can detect an empty string to find out if a line is blank or not. For example:
if(str!=null && str.trim().length()==0)
Or you can do (if using JDK 1.6 or later)
if(str!=null && str.isEmpty())
BufferedReader br = new BufferedReader(new FileReader("test.txt"));
String line;
int empty = 0;
while ((line = br.readLine()) != null) {
if (line.trim().isEmpty()) {
// Line is empty
}
}
The above code snippet can be used to detect if the line is empty and at that point you can create FileWriter to write to new file.
Something like this should do :
public static void main(String[] args) throws Exception {
writeToMultipleFiles("src/main/resources/fileIn.txt", "src/main/resources/fileOut.txt");
}
private static void writeToMultipleFiles(String fileIn, String fileOut) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(new File(fileIn))));
String line;
int counter = 0;
BufferedWriter wr = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(new File(fileOut))));
while((line=br.readLine())!=null){
if(line.trim().length()!=0){
wr.write(line);
wr.write("\n");
}else{
wr.close();
wr = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(fileOut + counter)));
wr.write(line);
wr.write("\n");
}
counter++;
}
wr.close();
}

Categories