I've encountered this weird thing which prevents me from creating a new line in a .txt file, using a BufferedWriter connected to a FileWriter. However, if I save the file as the default option, .file. The spaces would be included in the document. The referred part of the code below:
BufferedWriter writer = new BufferedWriter(new FileWriter(file));
for(Account acc : list) {
writer.write(acc.getFirst() + "," + acc.getLast() + "," + acc.getPassword() + "," + acc.getEmail() + "\n");
}
The values in the .write. method are all Strings.
Related
Writing a program in java I'm trying to read the content of a file which is treated as a storage. I have a function to modify the amount of an object in the store, which is organized with one line per product, where the first word is the prodCode, and the second is the amount of it.
This is the function:
public static void modifyAmount(String prodCode, String newAmount){
try{
File magazzino = new File("Magazzino.txt");
BufferedReader fromFile = new BufferedReader(new FileReader("Magazzino.txt"));
FileWriter toFile = new FileWriter(magazzino);
String oldContent="";
String line;
String lineToReplace = prodCode + " " + amountRequest(prodCode);
String newLine = prodCode + " " + newAmount;
while((line = fromFile.readLine()) != null){
oldContent = oldContent + line + "\n";
System.out.println("leggendo " + line);
}
System.out.println(oldContent);
String newContent = oldContent.replaceAll(lineToReplace, newLine);
toFile.write(newContent);
toFile.close();
fromFile.close();
}catch(IOException e){
e.printStackTrace();
}
}
And the result of it is that it won't enter the while cycle because the first readLine result null, though the file is correctly formatted, the 'amountRequest' function works properly and the input is correct.
Magazzino.txt:
1 12
3 25
4 12
You're probably having trouble because you're trying to read and write the file at the same time, with different file handles. I'd suggest reading the file first, then closing the FileReader, then creating a FileWriter to write to it.
The issue is that before you have read the contents of the file, you are creating an instance of FileWriter which will clear the file.
FileWriter toFile = new FileWriter("Magazzino.txt"); will clear the file
The solution is to just create the instance of FileWriter after you are done reading the file.
public static void modifyAmount(String prodCode, String newAmount){
try{
File magazzino = new File("Magazzino.txt");
BufferedReader fromFile = new BufferedReader(new FileReader("Magazzino.txt"));
String oldContent="";
String line;
String lineToReplace = prodCode + " " + amountRequest(prodCode);
String newLine = prodCode + " " + newAmount;
while((line = fromFile.readLine()) != null){
oldContent = oldContent + line + "\n";
System.out.println("leggendo " + line);
}
fromFile.close();
System.out.println(oldContent);
String newContent = oldContent.replaceAll(lineToReplace, newLine);
FileWriter toFile = new FileWriter(magazzino);
toFile.write(newContent);
toFile.close();
}catch(IOException e){
e.printStackTrace();
}
}
You open a file twice, simultaneously for reading and writing.
As soon as you do this line,
FileWriter toFile = new FileWriter(magazzino);
your file is erased. Check it yourself.
Actually, with this line you are creating a new empty file for writing instead of the old one.
I'd suggest read file, then close, then write.
You can also try to pen file for append : new FileWriter("filename.txt", true);
This will not erase old file, allowing you to read it. But the new data will be appended to the end, though.
If you want to use you file as a state or storage, I'd suggest to look at sqlite: https://www.sqlite.org/index.html
Hey so I'm currently having an issue with this code: [There is more code to this but this is the block that I need help with]
File fe = new File("C:\\Users\\" + System.getProperty("user.name") + "\\desktop" + "\\SearchResults.txt");
String customLoca = "C:\\Users\\" + System.getProperty("user.name") + "\\desktop";
File dir = new File(customLoca);
for (File f : dir.listFiles()){
if (f.getName().contains(".jar"))
if (f.getName().endsWith(".jar"))
try{
FileWriter fw = new FileWriter(fe);
fw.write("[!]Found: " + f.getName() + "[!]");
fw.write("\r\n");
fw.write("[!]Found: " + f.getName() + "[!]");
fw.close();
}catch(Exception ex){
}
}
}
}
I want it to print all the results however it only prints 1.
https://gyazo.com/406ab3039f3efa8f72d3dfff5732c088
Do you know a way I can make it so it prints all the results? Thanks.
The problem is that you are creating the file writer object inside loop. so it will replace the previous result hence only the last result will be present in the searchResults.txt.
To fix this problem move FileWriter fw = new FileWriter(fe); outside the for loop
Also note that you dont need both the 2 if conditions.
if if (f.getName().contains(".jar")) is true then
if (f.getName().endsWith(".jar")) also returns true, also you are missing the braces after the if statement.
File dir = new File(customLoca);
for (File f : dir.listFiles()){
if (f.getName().endsWith(".jar")) {
try{
FileWriter fw = new FileWriter(fe);
fw.write("[!]Found: " + f.getName() + "[!]");
fw.write("\r\n");
fw.write("[!]Found: " + f.getName() + "[!]");
fw.close();
}catch(Exception ex){
}
}
}
I'm trying to create a save feature which outputs stored data to a text file. I've tried using a Printwriter to write to the file and although I'm not getting any errors and the output seems to be correct, the text file remains blank. Here is my code:
public void saveConfiguration() throws IOException{
PrintWriter pw = new PrintWriter("locos.txt");
for (int i = 0; i < currentTrains.size(); i++) {
//confirm data is correct
System.out.println(currentTrains.get(i).getAddress() + " " +
currentTrains.get(i).getName() + " " + "\n");
//write to file
pw.write(currentTrains.get(i).getAddress() + " " +
currentTrains.get(i).getName() + " " + "\n");
}
pw.close();
//for testing
System.out.println("File Saved");
}
Here's what's on the console:
8 class 08
55 Jinty
44 BR44
File Saved
The above data that gets printed out is correct, but it's not getting written to the file. Can anyone explain how to do this properly?
Edit: I don't know if this is relevant, but I'm running this on a Tomcat server.
You should try handling the PrintWriter and a Filerwriter instead...
Example:
PrintWriter pw = new PrintWriter(new FileWriter("locos.txt"));
File outFile = new File("D:\\output.txt");
BufferedWriter wb = new BufferedWriter(new FileWriter(outFile));
while (resultSet.next()) {
int attr_id = resultSet.getInt("int_id");
String stringValue = resultSet.getString("StringValue");
String name = resultSet.getString("Name");
int index = stringValue.indexOf(".");
int valueLength = stringValue.length();
if(isNumeric(stringValue)) {
//if(index != -2 ) {
if(index != (valueLength - 2)) {
String string1 = Double.valueOf(stringValue).toString();
System.out.println("converted values : " +string1);
System.out.println("stringValue : " +stringValue);
System.out.println("intValue : " +int_id);
wb.write( stringValue + "," + int_id + "," + string1 );
wb.newLine();
}
}
}
Above is my part of the code, from resultset i'm writing the data into a file. However the code is not printing values in output.txt file but i could see the result in console.
if i remove the commented line and comment if(index != (valueLength - 2)) { this line, the java code is creating output.txt with values.
What's wrong?
probably need to just call flush and/or close on your BufferedWriter when you are done.
The reason why your code is not writing to the file is because you never push the data from the Writer to the actual file.
Think of BufferedWriters as an email you are sending to a coworker. When you use:
wb.write( stringValue + "," + int_id + "," + string1 );
it is like you are typing the email to your coworker, and defining the message to them. BUT, since you did not press "send email", your coworker will never see the message. The same concept can be applied here.
You are filling the writer with a bunch of data, but you are never sending the data to the file that you are trying to write to. There are two ways that you can do this, the first being to "flush" the writer (see documentation HERE). You can do this by calling
wb.flush();
This is the equivalent of pressing "send email", and will write the data to the file that you are editing. The second method would be to "close" the writer (see documenation HERE). The reason that this works is because the BufferedWriter's close method flushes the stream first, before closing the stream. This can be done by calling
wb.close();
Although, it would not be wise to do so until you are fully done editing the file, as it can no longer be accessed.
The following is your code edited to flush the stream after every record you are writing, and then close the stream after all records have been processed. Note the locations of wb.flush() and wb.close().
File outFile = new File("D:\\output.txt");
BufferedWriter wb = new BufferedWriter(new FileWriter(outFile));
while (resultSet.next()) {
int attr_id = resultSet.getInt("int_id");
String stringValue = resultSet.getString("StringValue");
String name = resultSet.getString("Name");
int index = stringValue.indexOf(".");
int valueLength = stringValue.length();
if(isNumeric(stringValue)) {
//if(index != -2 ) {
if(index != (valueLength - 2)) {
String string1 = Double.valueOf(stringValue).toString();
System.out.println("converted values : " +string1);
System.out.println("stringValue : " +stringValue);
System.out.println("intValue : " +int_id);
wb.write( stringValue + "," + int_id + "," + string1 );
wb.newLine();
wb.flush();
}
}
}
wb.close();
This question already has answers here:
Writing to an already existing file using FileWriter Java
(2 answers)
Closed 9 years ago.
I have been working with Files in Java. And I know the basics of reading and writing to/from files. Below is the code that I tried to write
void qlm(String option,String initiate,String ii,String file_path,String source,List destination){ //,String paths,String src){
String [] Ln = {"B","C","D"};
int count =1, counter=1,seq=1;
try{
System.out.println("Here: " +file_path);
PrintWriter pwr = new PrintWriter(new FileWriter(getHandleB()),true);
for(int i=0;i<Ln.length;i++){
pwr.println("Sequence_Number" + "|" + "QLM_Operation" + "|" + "II_D" + "|" + "Val_D" + "|" + "List" + "|" + "Type" + "|" + "Status" + "|" + "Source" + "|" + "Destination");
pwr.println(count + "|" + option + "|" + "DataK" + "|" + "Value" + "|" + Ln + "|" + "Null" + "|" + "Pending" + "|" + source + "|" + Ln[i]);
count++;
}
pwr.close();
getHandleB() is the path of the File. This is performed in the method qlm(parameters)
Now I want to write in the same File (path: getHandleB()) from a different method named handle(parameters)
The output of this function, should write in the same file without removing the contents of the previous method. When i try to write in the file, it removes the previous contents and writes the new one. How can I avoid this. I want all the contents from all the methods to be written. Thanks for all the help.
You are not appending to the File. Use the FileWriter constructor that allows for appending, that has a boolean/true as its second parameter.
PrintWriter pwr = new PrintWriter(new FileWriter(getHandleB(), true),true);
Edit
Separating out the constructor calls in my code above should help you to understand what's going:
FileWriter fileWriter = new FileWriter(getHandleB(), true);
PrintWriter pwr = new PrintWriter(fileWriter, true);
So you see that yes, there are two boolean parameters being used here, but they're being used with different constructors.
You need to use the appropriate FileWriter constructor with true as the second argument.
By default, a FileWriter truncates the file it opens.