Java get line total then write to specific line - java

I'm stuck on writing to a specific line using File, BufferedReader, & BufferedWriter.
What I'm trying to achieve is getting my text files total line count (-3) & writing to that line.
Currently it just erases the whole file & nothing is written.
Image of what I'm doing:
(In Image) line 25 is blank & 26 doesn't contain a doc. it contains "}"
& My code:
package com.tests.writer;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import javax.swing.JFrame;
public class NewWriter {
static Integer tableCount;
static File file;
static FileWriter fw;
static FileReader fr;
static BufferedWriter bw;
static BufferedReader br;
public static void main(String[] args) {
JFrame frame = new JFrame("Test {New Writer}");
frame.setBounds(500, 500, 500, 500);
frame.setVisible(true);
frame.setResizable(false);
frame.setAutoRequestFocus(true);
try {
startApplication();
} catch (IOException e) {
e.printStackTrace();
}
}
private static void startApplication () throws IOException {
writeToFile ();
}
private static void writeToFile () throws IOException {
Integer lineTCount = 0;
file = new File("Tables.txt");
if (file.exists()) {
fw = new FileWriter(file.getAbsolutePath(), true);
fr = new FileReader(file.getAbsolutePath());
bw = new BufferedWriter(fw);
br = new BufferedReader(fr);
for (String line = br.readLine(); line != null; line = br.readLine()) {
lineTCount++;
System.out.println(lineTCount);
}
System.out.println(lineTCount);
bw.write("Test Text to insert");
System.out.println("done");
System.exit(0);
} else {
file.createNewFile();
System.out.println("New File = " + file.toString());
writeToFile();
}
}
}
If there is an easier way of doing this, I'm open to all idea's as I'm still not familiar with Java.io
& If anyone can tell me this is correct. I may have to add the whole file to a list, add the new text then re-write the file.

There are a few things you did a little bit off.
First and foremost; the reason your file is returning empty is because you aren't calling
bw.close();
After you have finished writing to the file.
I don't know of any way to write to a specific part of a file. I don't think there is one.
What you'll have to do is re-write the file. Basically, make a temporary copy, then write all the lines just as before, except for the third-to-last one.
See this question:
I want to open a text file and edit a specific line in java
(I don't know how to mark questions as duplicate)
BufferedWriter's 'write(String s, int off, int len)' method actually states
Writes a portion of a String.
Note; that is NOT 'writes to a specific location in the file'.
EDIT
I wouldn't use System.exit(0);. That tells your OS 'This execution failed'. You should just let your program close itself normally by excluding this line.
See: When to use system.exit(0)?

The bw pointer does not move when you loop through your file. Use this to write to a specific location in your file. Also why are there two variables lineCount & lineTCount
public void write(String s,
int off,
int len)
throws IOException
Ref: http://docs.oracle.com/javase/7/docs/api/java/io/BufferedWriter.html#write(java.lang.String,%20int,%20int)
EDIT: you are right, my bad. You will have to read the previous contents -> make the changes that you want and rewrite the whole file again.

Related

How can I insert text before and after each line of a text file?

Below is my code that reads in a file, and then writes its contents to a new file. What I need to do is add in text between each line of text from the old file and put that in the new file. In this code, the file is read as a whole, so how do I change it to go through line by line and add text between each?
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.List;
public class Webpage {
public static String readTextFile(String fileName) throws IOException {
String content = new String(Files.readAllBytes(Paths.get(fileName)));
return content;
}
public static List<String> readTextFileByLines(String fileName)throws IOException {
List<String> lines = Files.readAllLines(Paths.get(fileName));
return lines;
}
public static void writeToTextFile(String fileName, String content)throws IOException {
Files.write(Paths.get(fileName), content.getBytes(), StandardOpenOption.CREATE);
}
}
I think your readTextFileByLines will do what you want. You can iterate through the List and write out whatever you want before and after each line.
If you must use the readTextFile method, you could use split("\n") to turn the single big String (the whole file) into an array of Strings, one per line.
Hmm... the doc for Split (one argument) says that trailing empty strings won't be included in the result. So if your input file might contain empty lines at the end, you should use the two argument split with a very large second argument: split("\n", Long.MAX_VALUE);
Read the text file line by line and add new lines where you wish.
Put the read values with new lines in a string per line separated by \n.
Write in new text file.
If what you are trying to do is re-write each line with the same string before and after each time than you can use this code:
public static void main(String[] args) throws IOException {
addLines("/Users/Hamish/Desktop/file1.txt", "/Users/Hamish/Desktop/file2.txt");
}
public static void addLines(String fileName, String secondFile) throws IOException {
File file = new File(fileName);
FileReader fr = new FileReader(file);
BufferedReader br = new BufferedReader(fr);
String line = null;
PrintWriter writer = new PrintWriter(secondFile, "UTF-8");
while ((line = br.readLine()) != null) {
writer.println("Random line before");
writer.println(line);
writer.println("Random line after");
}
br.close();
writer.close();
}
Effectively it reads the txt file line by line and before and after each line it will print something you specify.
If you want at the end you can also write:
file.delete();
to remove the first file.
If what you want to write before and after each line is specific than unfortunately I can't help you.

Reading/writing files line-by-line reporting position

I wish to read and write some files line-by-line.
My first thoughts were to use BufferedReader and BufferedWriter but my gotcha is that I need to know how far through the files I am.
When reading I would like to who how far through processing the file I am and I would like it to be accurate, so after every readLine() I am expecting the position to update, this is complicated by the fact that there is a buffer involved.
Same applies to writing, I need to get the position accurately before and after writing a line. I'm guessing this isn't as difficult as my understanding is that a BufferedWriter flushes after every newline char anyways, so given that I am writing lines, I could just write straight to the channel.
Before I reinvent the wheel here, or use some dodgy reflection, is there anything in the JDK that can help me out here?
EDIT: Just to clear things up, I am looking for byte positions.
It wasn't entirely clear based on your question what you mean by "how far through processing the file I am". Does that mean line number or byte position?
If it means line number, there are really two options:
A) Keep a track of the line numbers manually. Shouldn't be that hard. Just increment a counter for every line.
B) Use java.io.LineNumberReader as suggested by #Jesper
If it means byte position, increment the byte position counter by each line length and don't forget to include the newlines in the byte position as well.
When writing, there is no LineNumberWriter so you need to keep track of the counters manually. Shouldn't be hard.
see below example for reading file using RandomAccessFile
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.Timer;
import java.util.TimerTask;
public class ConsoleReader {
/**
* #param args
*/
public static void main(String[] args) {
File file = new File("fileName");
try {
RandomAccessFile r = new RandomAccessFile(file, "r");
//First time read
String str = null;
while((str = r.readLine()) != null) {
System.out.println(str);
}
r.seek(r.getFilePointer());
startTimer(r);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
private static void startTimer(final RandomAccessFile r) {
Timer timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
String str = null;
try {
while((str = r.readLine()) != null) {
System.out.println(str);
}
r.seek(r.getFilePointer());
} catch (IOException e) {
e.printStackTrace();
}
}
}, 0, 1000);
}
}

How to create and write a .Txt file in Java? [duplicate]

This question already has an answer here:
Java PrintWriter not working
(1 answer)
Closed 6 years ago.
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class FileGenerator {
/**
* #param args
*/
public static void main(String[] args) {
File outputFile;
BufferedReader reader;
FileWriter fileWriter;
try {
outputFile = new File("test.txt");
outputFile.createNewFile();
fileWriter = new FileWriter(outputFile, false);
reader = new BufferedReader(new FileReader("template.txt"));
StringBuilder sb = new StringBuilder();
String line = reader.readLine();
while (line != null) {
sb.append(line);
sb.append(System.lineSeparator());
line = reader.readLine();
}
String everything = sb.toString();
fileWriter.write(everything);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
}
}
}
The fileWriter creates test.txt but the string inside of test.txt is empty. i want it doesnt happen empty. by the way you may say "String everything" can be empty. But it isnt. When i try without reader txt i mean "String everything = "some text", it happens same. it happens empty
The file is empty because the contents of everything are smaller than the operating systems and / or Java's I/O buffers, and the program ends without properly closing the file.
When you write something to a file, and you need to ensure that it is written without closing the file already, call flush().
Whenever you open an I/O resource, close it using close() after use. close() implies flushing the buffers.
Java 7 provides try-with-resources for that, like this:
try (FileWriter writer = new FileWriter("foo.txt")) {
writer.write("Hello, world!\n");
writer.flush();
// do more stuff with writer
} // <- closes writer implicitly as part of the try-with-resources feature
As suggested in the comments, you need to do fileWriter.close() in order to close the output stream. If it is a buffered writer, then closing it not necessary as explained here.
Is it necessary to close a FileWriter, provided it is written through a BufferedWriter?

why is Scanner's hasNext() method initially returning false for a non-empty text file?

I'm trying to write some text to a file. I have a while loop that is supposed to just take some text and write the exact same text back to the file.
I discovered that the while loop is never entered because Scanner thinks there's no more text to read. But there is.
import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
public class WriteToFile {
public static void main(String[] args) throws FileNotFoundException {
String whatToWrite = "";
File theFile = new File("C:\\test.txt");
Scanner readinput = new Scanner(theFile);
PrintWriter output = new PrintWriter(theFile);
while (readinput.hasNext()) { //why is this false initially?
String whatToRead = readinput.next();
whatToWrite = whatToRead;
output.print(whatToWrite);
}
readinput.close();
output.close();
}
}
The text file just contains random words. Dog, cat, etc.
When I run the code, text.txt becomes empty.
There was a similar question: https://stackoverflow.com/questions/8495850/scanner-hasnext-returns-false which pointed to encoding issues. I use Windows 7 and U.S. language. Can I find out how the text file is encoded somehow?
Update:
Indeed, as Ph.Voronov commented, the PrintWriter line erases the file contents! user2115021 is right, if you use PrintWriter you should not work on one file. Unfortunately, for the assignment I had to solve, I had to work with a single file. Here's what I did:
import java.util.ArrayList;
import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
public class WriteToFile {
public static void main(String[] args) throws FileNotFoundException {
ArrayList<String> theWords = new ArrayList<String>();
File theFile = new File("C:\\test.txt");
Scanner readinput = new Scanner(theFile);
while (readinput.hasNext()) {
theWords.add(readinput.next());
}
readinput.close();
PrintWriter output = new PrintWriter(theFile); //we already got all of
//the file content, so it's safe to erase it now
for (int a = 0; a < theWords.size(); a++) {
output.print(theWords.get(a));
if (a != theWords.size() - 1) {
output.print(" ");
}
}
output.close();
}
}
PrintWriter output = new PrintWriter(theFile);
It erases your file.
You are trying to read the file using SCANNER and writing to another file using PRINTWRITER,but both are working on same file.PRINTWRITER clear the content of the file to write the content.Both the class need to work on different file.

How can I write from the ArrayList to file, each element from the ArraList in a new line?

What I wanted to do is convert an ArrayList to file and after that, use the file line per line.
My code:
List<String> Inserts = new ArrayList<String>();
String FileToLoad = null;
.
.
.
.
FileToLoad = prpfile.properties();
System.out.println(FileToLoad);
FileWriter writer = new FileWriter(FileToLoad);
for (String str : Inserts) {
writer.write(str);
}
writer.close();
String QueryNewData = "LOAD DATA LOCAL INFILE '" + FileToLoad + "' INTO TABLE companies FIELDS TERMINATED BY ',' (Name,Address,NumberDUG,post,status)";
UpdateDatabase LoadNewData = new UpdateDatabase();
LoadNewData.LoadQuery(QueryNewData);
Onces the code run, the file is created correctly but it's made the wholw ArrayLIst in one single line. How could inlude a new line for each element in the ArrayList?
Apart from the obvious things that are wrong with your code:
naming convention not followed
stream not closed in finally {}
...
You must remember that a simple writer does not magically append line feeds, you could wrap it in a printwriter which has a println() much like System.out or you could do as the other answer suggest (i.e.) add a line feed manually.
However for cross-platform reasons I would suggest:
writer.write(str + System.getProperty("line.separator"));
Wrap your FileWriter in a BufferedWriter. Javadoc. FileWriter has the newLine() method.
Other option is to write the new line using System.lineSeparator(), which is cross-platform.
if you really want to use it simple way than others suggested, you can use printwriter as it have println() method which takes string as parameter.
PrintWriter pw = new PrintWriter(FileToLoad);
for(int index=0;index<Inserts.size();index++)
{
pw.println(arrayList.get(index));
}
//pw.flush(); not needed since by default its enabled
Solution:
package com.test;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class CreateFileFromList {
public static void main(String[] args) throws IOException {
List<String> list = new ArrayList<String>();
list.add("This is line 1.");
list.add("This is line 2.");
list.add("This is line 3.");
File f = new File ("C:\\temp\\Sample.txt");
if (!f.exists()) {
f.createNewFile();
}
FileWriter fw = new FileWriter(f.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
for(String s : list) {
bw.write(s + System.getProperty("line.separator"));
}
bw.close();
}
}
New file Sample.txt will be created on c:\temp directory along with below contents:
This is line 1.
This is line 2.
This is line 3.

Categories

Resources