I want to write a new line using a FileOutputStream; I have tried the following approaches, but none of them are working:
encfileout.write('\n');
encfileout.write("\n".getbytes());
encfileout.write(System.getProperty("line.separator").getBytes());
This should work. Probably you forgot to call encfileout.flush().
However this is not the preferred way to write texts. You should wrap your output stream with PrintWriter and enjoy its println() methods:
PrintWriter writer = new PrintWriter(new OutputStreamWriter(encfileout, charset));
Alternatively you can use FileWriter instead of FileOutputStream from the beginning:
FileWriter fw = new FileWriter("myfile");
PrintWriter writer = new PrintWriter(fw);
Now just call
writer.println();
And do not forget to call flush() and close() when you finish your job.
It could be a viewer problem... Try opening the file in EditPlus or Notepad++. Windows Notepad may not recognize the line feed of another operating system. In which program are you viewing the file now?
String lineSeparator = System.getProperty("line.separator");
<br>
fos.write(lineSeparator.getBytes());
To add a line break use
fileOutputStream.write(10);
here decimal value 10 represents newline in ASCII
Related
I have a.txt list trying to move the first line to the last line in Java
I've found scripts to do the following
Find "text" from input file and output to a temp file. (I could set
"text" to a string buffRead.readLine ??) and then...
delete the orig file and rename the new file to the orig?
Please for give me I am new to Java but I have done a lot of research and can't find a solution for what I thought would be a simple script.
Because this is Java and concerns file IO, this is a non-trivial setup. The algorithm itself is simple, but the symbols required to do so are not immediately evident.
BufferedReader reader = new BufferedReader(new FileReader("fileName"));
This gives you an easy way to read the contents of the file fileName.
PrintWriter writer = new PrintWriter(new FileWriter("fileName"));
This gives you a simple way to write to the file. The API to do so is the exact same as System.out when you use a PrintWriter, thus my choice to use one here.
At this point its a simple matter of reading the file and echoing it back in the correct order.
String text = reader.readLine();
This saves the first line of the file to text.
while (reader.ready()) {
writer.println(reader.readLine());
}
While reader has text remaining in it, print the lines into the writer.
writer.println(text);
Print the line that you saved at the start.
Note that if your program does anything else (and it's just a good habit anyway), you want to close your IO streams to avoid leaking resources.
reader.close();
writer.close();
Alternatively, you could also wrap the entire thing in a try-with-resources to perform the same cleanup automatically.
Scanner fileScanner = new Scanner(myFile);
fileScanner.nextLine();
This will return the first line of text from the file and discard it because you don't store it anywhere.
To overwrite your existing file:
FileWriter fileStream = new FileWriter("my/path/for/file.txt");
BufferedWriter out = new BufferedWriter(fileStream);
while(fileScanner.hasNextLine()) {
String next = fileScanner.nextLine();
if(next.equals("\n") out.newLine();
else out.write(next);
out.newLine();
}
out.close();
Note that you will have to be catching and handling some IOExceptions this way. Also, the if()... else()... statement is necessary in the while() loop to keep any line breaks present in your text file.
Add the same line to the last line of this file have a look into this link https://stackoverflow.com/a/37674446/6160431
Im building a Car Rental program and what I want it to, for now, is:
Register a user
Register a car
using .txt files to store the data.
With the code I've written, I can register only a single car and user. Every time I run the register method for client or car, the last register is erased.
Can you help me with this? Also, later I'm going to implement a way to rent a car, but I don't know how to do that also, so if you have any ideas of how to do it, please tell me!
Also I intend to do it without SQL or such things.
This is the code I'm using to register a user (I'm using netbeans with JForm):
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
String nomeClient = txtNomeClient.getText();
String idClient = txtIdClient.getText();
File file = new File("clients.txt");
try {
PrintWriter output = new PrintWriter(file);
output.println(nomeClient);
output.println(idClient);
output.close();
JOptionPane.showMessageDialog(null, "Client registed!");
} catch (FileNotFoundException e) {
}
}
The problem is that you overwrite the existing file clients.txt, instead of appending to it by calling new PrintWriter(file). You can use the following code:
FileWriter fileWriter = new FileWriter(file, true);
PrintWriter output = new PrintWriter(fileWriter));
This way, you append the end of the file, see the constructor FileWriter(File file, boolean append). The documentation describes it perfectly:
Constructs a FileWriter object given a File object. If the second argument is true, then bytes will be written to the end of the file rather than the beginning.
The FileWriter is just used to open a file in append mode, as PrintWriter does not have a suitable constructor to do that directly. You could also write characters with it, but a PrintWriter allows for formatted output. From the documentation of FileWriter:
Convenience class for writing character files. The constructors of this class assume that the default character encoding and the default byte-buffer size are acceptable.
The PrintWriter uses the FileWriter passed in its constructor to append to the destination file, see here for a good explanation. As stated there, you could also use an FileOutputStream. There are multiple ways to do this.
Here is an example using a FileOutputStream and a BufferedWriter, which supports buffering and can reduce unnecessary writes that penalize performance.
FileOutputStream fileOutputStream = new FileOutputStream("clients.txt", true);
BufferedWriter bufferedWriter = new BufferedWriter(fileOutputStream);
PrintWriter printWriter = new PrintWriter(bufferedWriter);
Does anyone knoe how to save specific Jmeter Variables into a csv file?
I have already tried this topic with no succes: Write extracted data to a file using jmeter and this code:
FileWriter fstream = new FileWriter("result.csv",true);
BufferedWriter out = new BufferedWriter(fstream);
out.write(${account_id});
out.close();
Thank you.
Replace your out.write(${account_id}); stanza with out.write(vars.get("account_id"));
It is better to close fstream instance as well to avoid open handles lack
If you're going to reuse this file, i.e. store > 1 variable, add a separator, i.e. new line
Final code:
FileWriter fstream = new FileWriter("result.csv",true);
BufferedWriter out = new BufferedWriter(fstream);
out.write(vars.get("account_id"));
out.write(System.getProperty("line.separator"));
out.close();
fstream.close();
See How to use BeanShell: JMeter's favorite built-in component for comprehensive information on Beanshell scripting
You can use this code in your BeanShellPostProcessor. It may help You.
String acid="${account_id}";
FileWriter fstream = new FileWriter("result.csv",true);
fstream.write(acid+"\n");
fstream.close();
I have one scenario where I am trying to implement with the Java 7 'try with resource' feature.
My finally block contains an object of BufferedWriter and File, which I want to close using 'try with resource' feature, instead of closing it by calling close method explicitly.
But I checked on net and saw that the File class does not implement the AutoCloseable interface, but BufferedWriter does. So how can I manage this scenario to implement 'try with resource' feature?
try (BufferedWriter br = new BufferedWriter(new FileWriter(path)))
Use this simply, br will be closed automatically.
Eg. http://www.roseindia.net/java/beginners/java-write-to-file.shtml
You don't need to close a File because it's a pure Java object. It basically just holds the name of the file, nothing else (i.e. it does not require any OS resources to construct).
You only need to close your BufferedWriter and that is correctly AutocCloseable.
You cannot create a BufferedWriter with File only, BufferedWriter requires a Writer, this how it should look like
try (BufferedWriter w = new BufferedWriter(new FileWriter(new File("file")))) {
...
}
try-with-resources will call close only on BufferedWriter. Unfortunately BufferedWriter API does say that it closes the underlying writer, but in fact it does. As for File it has nothing to do with try-with-resources since it is not Autocloseable.
I know how to create a PrintWriter and am able to take strings from my gui and print it to a text file.
I want to be able to take the same program and print to the file adding text to the file instead of replacing everything already in the text file. How would I make it so that when more data is added to the text file, it is printed on a new line every time?
Any examples or resources would be awesome.
try
{
PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("outfilename", true)));
out.println("the text");
out.close();
} catch (IOException e) {
}
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.
PrintWriter writer=new PrintWriter(new FileWriter(new File("filename"),true));
writer.println("abc");
FileWriter constructor comes with append attribute,if it is true you can append to a file.
check this
Your PrintWriter wraps another writer, which is probably a FileWriter. When you construct that FileWriter, use the constructor that takes both a File object and an "append" flag. If you pass true as the append flag, it'll open the file in append mode, which means that new output will go at the end of the file's existing contents, rather than replacing the existing contents.