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"));
Related
I am wanting to store some variables in a .txt file for storage and have attempted to use the PrintWriter functions, however the txt file i am trying to create doesn't actually create, let alone write to the file!
Code:
if(new String("SimpleBLEBroadcaster").equals(result.getDevice().getName()))
peripheralTextView.append("Device Name: " + result.getDevice().getName() + " rssi: " + result.getRssi() +" Packet length: " + PacketLength + " Packet Data: " + "0x" + R + "\n");
File myObj = new File("C:\\Users\\Josh Gascoigne\\Documents\\Uni stuff\\Android Studio\\Data.txt");
PrintWriter DataOut = null;
try {
DataOut = new PrintWriter("Data.txt");
} catch (FileNotFoundException e) {
e.printStackTrace();
}
DataOut.println(R);
DataOut.close();
I have followed a few tutorials on how best to use the print writer function and copied a youtube tutorial but using my variables and i cant understand why the txt file isnt being created. i even tried generating the file prior to writing to it. Any help would be much appreciated.
Your constructor for PrintWriter should be as follows;
DataOut = new PrintWriter(myObj);
Refer: PrintWriter
----------------Explanation-----------------
What your code is doing is that the PrintWriter is not referring to the same file that you are instantiating in the code above.
File myObj = new File("C:\Users\Josh Gascoigne\Documents\Uni stuff\Android Studio\Data.txt");
What you code is possibly doing is creating a new file Data.txt in the working directory of the program.
So basically, you referring to the file C:\\Users\\Josh Gascoigne\\Documents\\Uni stuff\\Android Studio\\Data.txt is redundant.
Referring to the variable myObj in the PrintWriter constructor should fix that redundancy. (Provided that is what your use case is.)
There's no such path as c:\ on any Android device.
Then your print writer too.
You didn't even specify any path.
At least try something like
File destination = new File(getExternalFilesDir(null), "data.txt");
Dataout = new PrintWriter(destination);
Dataout.println(R);
Dataout.close();
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'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.
I have this code here that takes in 3 arguments, A Directory, a Filename, and a number. The program creates the filename in the directory and writes the number in it. So I can say...
>java D: myName.txt Clay 100
which will create a file named myName.txt in D: and says 100 in it.
If myName is taken up, it changes the name to myName(2), then myName(3) (if myName(2) taken up). The only problem is that when it changes the name to myName(2) and writes, it overwrites myName. I dont want it to overwrite myName, I want it to just create a new file with that name. Ive looked at similar questions and the common answer is the flush and close the writer which ive done And it still doesnt work.
Any help would be appreciated, here is my code so fart...
import java.io.*;
public class filetasktest{
public static void main(String[] args) throws IOException{
int i = 2;
String directory = args[0];
if (directory.substring(directory.length() - 1) != "/"){
directory += "/";
}
String contactName = args[1];
String contactNumber = args[2];
String finalDirectory = directory + contactName + ".contact";
File f = new File(finalDirectory);
while (f.exists()){
finalDirectory = directory + contactName + "(" + ("" + i) + ")" + ".contact";
f.renameTo(new File(finalDirectory));
i++;
}
Writer writer = null;
try {
writer = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream(finalDirectory), "utf-8"));
writer.write(contactNumber);
} catch (IOException ex){
System.out.println(ex.getMessage());
} finally {
try {
writer.close();
} catch (Exception ex) {
System.out.println(ex.getMessage());
}
}
}
}
You need to use append mode
new BufferedWriter(new FileWriter(yourFileName, true));
here, true means that the txt should be appended at the end of file.
Check the FileWriter javadoc for more information.
Your problem is here:
while (f.exists()){
finalDirectory = directory + contactName + "(" + ("" + i) + ")" + ".contact";
f.renameTo(new File(finalDirectory));
i++;
}
The renameTo method does not change the path of a File object; it renames a file on disk. The path of f stays the same throughout the loop: it starts out as D:/myName.txt and if a file by that name exists, the file is renamed as D:/myName(1).txt. The variable f still holds the path D:/myName.txt, which no longer names a file, and the content is written to D:/myName(1).txt, overwriting the previous content.
To fix this issue change the loop to:
while (new File(finalDirectory).exists()){
finalDirectory = directory + contactName + "(" + ("" + i) + ")" + ".contact";
i++;
}
Take a look at FileInputStream(String, boolean) which will allow you to flag if the file should be appended or overwritten