File and Filewriter - java

I need a way to delete a line, im using this to write on the file:
FileWriter insert = new FileWriter(file, true);
PrintWriter out = new PrintWriter(insert);
out.println("1. Mario");
I made a thing that reads line by line but i've no idea how to delete the string that returns, is that even possible?

While you're reading in the lines of text write then lines you want to keep to a StringBuffer or StringBuilder then write the contents of the buffer/builder back to the file. Is there any specific reason that you're opening up the file for appending when you're wanting to remove lines of text from the file or am I missing something?

Related

Best strategy to add lines of text to a text file

I'm using txt files, creating them with the class PrintWriter. This allows me to print inside a txt file some content using println(...) method.
But now I need to add some content at the end of the list that I created. Like this:
PrintWriter writer = new PrintWriter("File.txt", "UTF-8");
writer.println("Hello");
writer.println("Josh!");
writer.close();
the result is a file like this:
Hello
Josh!
but what if I would like to add new words at the bottom of the text? I would prefer an overwriting of the file "File.txt" with the content updated?
Hello
Josh!
How are you?
I was thinking on something like, "Ok I have to add another line at the end, so read all the file, and write another file (with the same name and content) adding a new line at the end", but it seems too strange to do, I feel like there is another simple way to do it. Any other idea?
You could simply use a FileWriter instead, it has an append mode that you can enable:
FileWriter writer = new FileWriter("File.txt");
writer.write("Hello\n");
writer.write("Josh!\n");
writer.close();
writer = new FileWriter("File.txt", true);
writer.append("Great!");
writer.close();
Your suspicions are correct.
You should use try with resources (Java 7+):
try(PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("File.txt", true)))) {
out.println("How are you?");
}catch (IOException e) {
//exception handling left as an exercise for the reader
}
The second parameter to the FileWriter constructor will tell it to append to the file (as opposed to clearing the file). Using a BufferedWriter is recommended for an expensive writer (i.e. a FileWriter), and using a PrintWriter gives you access to println syntax that you're probably used to from System.out. But the BufferedWriter and PrintWriter wrappers are not strictly necessary.
Also this allows you to append to a file, rather than replacing the whole file, on every run. Lastly, try with resources means you do not have to call .close(), it's done for you! Grabbed from here

BufferedWriter to write to file

I am reading a file using BufferedReader in java. Here are the sequence of operations that I am trying to do as reading the file
Keep reading up to certain length of characters in the file
Once it reads up to the length, do some manipuation on the read string
Write the read string to a temp file
Reset all the counters (ex. counter of the length)
Go back #1 and do this again for rest of file
What I am trying to figure out is #3. I want to append to temp file as I am writing to file using BufferedWriter. I know there is append() but, that looks like it write to new line. However, I want to write to next cursor each time. Basically, i want to preserve the format of the original file. Make a exact same file except some value being changed.
I hope this make sense.
thanks.
You can use a FileWriter by passing true as the second argument to its constructor. This will cause the FileWriter to append to the end of the file rather than overwrite the existing contents.
http://docs.oracle.com/javase/6/docs/api/java/io/FileWriter.html
BufferedWriter writer = new BufferedWriter(new FileWriter(file, true));
//calls to write will now append
append() will work just fine. You could even do just plain write(). If you want to write a new line with a BufferedWriter you would do this
BufferedWriter buff = new BufferedWriter();
buff.newLine();
For writing you can use PrintWriter
java.io.PrintWriter pw = new PrintWriter(new FileWriter(file, true));

Inserting New Lines when Writing to a Text File in Java

I have a slight delema with learning FileWriter... The ultimate goal is writing a program that will "spawn" a .bat file that will be executed by the batch code that launched the .jar. The problem is, I have no clue how to make sure that every FileWriter.write(); will print on a new line... Any ideas??
To create new lines, simply append a newline character to the end of the string:
FileWriter writer = ...
writer.write("The line\n");
Also, the PrintWriter class provides methods which automatically append newline characters for you (edit: it will also automatically use the correct newline string for your OS):
PrintWriter writer = ...
writer.println("The line");
Use a BufferedWriter and use writer.newLine() after every write-operation that represents one line.
Or, use a PrintWriter and writer.println().
If you are using BufferedWriter then you can use an inbuilt method :
BufferedWriter writer = Files.newBufferedWriter(output, charset);
writer.newLine();

how to append block of file to another file

I have a requirement that I need to append block of a file to other file.
let say I have 100 lines in source file and I need to append the 50 lines from the bottom to destination file.
To navigate to the 50th line I using .readLine() of the BufferedReader.
Once I reached to 50 th line I want to append remaining content to the destination file.
I don't want to append line by line as it is consuming much time.
Please help me how to do that..
Please provide a code snippet if possible.
read the file line by line and append in StringBuffer object
for eg
StringBuffer lineBuffer = new StringBuffer();
String line = "";
while((line=br.readLine())!=null){
///// any condition or anything you want to do
lineBuffer.append(line);
}
now after you get the lines into the stringbuffer object write this into another file

How to append to the end of a file in java?

...
Scanner scan = new Scanner(System.in);
System.out.println("Input : ");
String t = scan.next();
FileWriter kirjutamine = new FileWriter("...");
BufferedWriter out = new BufferedWriter(writing);
out.write(t)
out.close();
...
if I write sometring into the file, then it goes to the first line. But if run the programm again, it writes the new text over the previous text (into the first line). I want to do: if I insert something, then it goes to the next line. For example:
after 1 input) text1
after 2 input) text1
text2
and so on...
what should i change in the code?
thanks!
java.io.PrintWriter pw = new PrintWriter(new FileWriter(fail, true));
This should do it. Use that over the existing pw line.
edit: And as explained in the comments, this is causing the following things to happen:
A FileWriter is being created, with the optional 'append' flag being set to true. This causes FileWriter to not overwrite the file, but open it for append and move the pointer to the end of the file.
PrintWriter is using this FileWriter (as opposed to creating its own with the file you pass it.)
(A lot of editing going on here. I was uncertain about the question a few times.)
I suggest you use the append flag in the FileWriter constructor.
You also might line to add a newline between each write ;)
why dont you use RandomAccessFile?
In RandomAccessFile, read/write operations can be performed at any position.The file pointer can be moved to anyplace by seek() method. You have to specify file opening mode while using it.
Example:
RandomAccessFile raf = new RandomAccessFile("anyfile.txt","rw"); // r for read and rw for read and write.
and to take the file pointer to EOF you have to use seek().
raf.seek(raf.length());
Instead of using BufferedWriter, use
PrintWriter out = new PrintWriter(kirjutamine);
out.print(t);
out.close();

Categories