...
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();
Related
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
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));
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();
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?
I have to edit the contents of a file and write the edited conted to another file.Here is the code iam using .
import java.io.*;
import java.util.*;
public class TestRef {
ArrayList<String> lines = new ArrayList<String>();
String line= null;
public void printThis(){
try{
FileReader fr = new FileReader("C:\\Users\\questions.txt");
BufferedReader br = new BufferedReader(fr);
FileWriter fw = new FileWriter("C:\\Users\\questions_out.txt");
BufferedWriter out = new BufferedWriter(fw);
while((line=br.readLine()) != null) {
if(line.contains("Javascript"))
line.replace("Javascript"," JAVA");
lines.add(line);
out.write(line);
}
}
catch(Exception e){}
}
public static void main(String [] args){
TestRef tr = new TestRef();
tr.printThis();
}
}
So this is like reading one line at a time and printing it back to the file. But when I execute this code the output file is blank.? Can you please provide me with a sample code, how to read from a file, make change in the content and write the whole file to a new file ?
Well, a few problems:
You're never closing either your input or your output. Closing will also flush - it's possible that something's just not being flushed. You should close stream-based resources in a finally block, so that they end up being closed even in the face of an exception. (Given that you should be closing, I wouldn't bother explicitly flushing as well. Just make sure you close the top-level abstraction - i.e. out (and br).
You're catching Exception and then swallowing it. It could well be that an exception is being thrown, but you're not able to tell because you've swallowed it. You should at least be logging it, and probably stopping at that point. (I'd also suggest catching IOException instead of Exception.)
You're using FileWriter and FileReader which doesn't allow you to specify the input/output encoding - not the issue here, but personally I like to take more control over the encodings I use. I'd suggest using FileInputStream and FileOutputStream wrapped in InputStreamReader and OutputStreamWriter.
You're calling String.replace() and ignoring the result. Strings are immutable - calling replace won't change the existing string. You want:
line = line.replace("Javascript"," JAVA");
You're never using your lines variable, and your line variable would be better as a local variable. It's only relevant within the method itself, so only declare it in the method.
Your code would be easier to follow if it were more appropriately indented. If you're using an IDE, it should be able to do this for you - it makes a huge difference in readability.
The first one is the most likely cause of your current problem, but the rest should help when you're past that. (The point about "replace" will probably be your next issue...)
You are missing out.flush().
BufferedWriters don't write anything until either you flush them, or their buffer fills up.
Close the print writer, outside the loop.
out.flush();
out.close();
Moreover you are writing strings to new lines, if you just want to replace javascript with Java, then you might also wanna write '\n', next line character to new file where old file contains new line.