Java Directory Search - Text File Writer - Only 1 result appears - java

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){
}
}
}

Related

PrintWriter not writing to text file

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"));

Java — Log file only saving the latest item

I am writing an app in Java (new developer) and I am trying to save messages and things like that within a log file (logs/[date].txt). The problem I am getting is that it's overwriting each time, rather than appending the values to my file.
Here is my code:
public void onMessage(String channel, String nick, String account, String hostname, String message) {
SimpleDateFormat sdf = new SimpleDateFormat("hh:mm:ss dd/MM/yyyy");
SimpleDateFormat sdfd = new SimpleDateFormat("dd/MM/yyyy");
Date now = new Date();
try {
/* Check if the logs folder exists */
File logdir = new File("logs/");
boolean result = true;
if (!logdir.exists()) {
try {
logdir.mkdir();
}catch(Exception e){
System.err.println("[ERROR] Could not make directory 'logs/'");
result = false;
}
}
/* Check if the log file exists */
File fcheck = new File("logs/" + sdfd.format(now).replace("/", "-") + ".txt");
if (!fcheck.exists()) {
try {
fcheck.createNewFile();
}catch (Exception e){
System.err.println("[ERROR] Could not make log file 'logs/" + sdfd.format(now).replace("/", "-") + ".txt'");
}
}
/* Write to file */
if (result) {
FileWriter file = new FileWriter("logs/" + sdfd.format(now).replace("/", "-") + ".txt");
PrintWriter write = new PrintWriter(file);
String entry = "[" + sdf.format(now) + "] [" + channel + "] " + nick + " (" + account + ") > " + message + "\n";
write.append(entry);
write.close();
file.close();
}else{
System.err.println("[ERROR] Could not save line to log file.");
}
}catch (Exception e){
System.err.println("[ERROR] Could not save line to log file.");
}
}
Sorry if this isn't amazingly clear, but I'm still learning Java.
As you can see, I have write.append(entry); — which I thought would append \n to my log file, thus allowing me to save and save and keep all the entries.
You are closing the PrintWriter on every entry - a new instance is created everytime you call that method and the file is overwritten.
If you do not want to change this, you can set the FileWriter to append mode by using FileWriter(String, boolean).
FileWriter file = new FileWriter("logs/" + sdfd.format(now).replace("/", "-") + ".txt", true);
PrintWriter write = new PrintWriter(file);
When creating object of type File , add second parameter true , and the file will be appended
FileWriter fcheck = new FileWriter("logs/" + sdfd.format(now).replace("/", "-") + ".txt",true);
Set the append parameter of FileWriter to true:
FileWriter file = new FileWriter("logs/" + sdfd.format(now).replace("/", "-") + ".txt", true);

Java PrintWriter doesn't append to existing .txt file after closing

I've run into some problems trying to append to an existing text file.
It doesn't seem to append a line text. So far i've got this method:
public static void addLine(File f, String line) {
try {
FileWriter fw = new FileWriter(f.getName(), true);
BufferedWriter buffer = new BufferedWriter(fw);
PrintWriter pw = new PrintWriter(buffer);
pw.println(line);
pw.close();
} catch (IOException e) {
System.err.println("IOException: " + e.getMessage());
}
}
and in my main i've got the following:
public static void main(String[] args) {
File f = new File("adresOfFile");
if (f.exists() && !f.isDirectory()) {
System.out.println("File " + f.getName() + " exists!");
System.out.println("\n" + "Path: " + f.getAbsolutePath());
System.out.println("\n" + "Parent: " + f.getParent());
System.out.println("\n" + "--------------CONTENT OF FILE-------------");
addLine(f, "");
addLine(f, "The line to append");
try {
displayContent(f);
} catch (IOException e) {
System.out.println(e.getMessage());
}
} else {
System.out.println("File not found");
}
}
When I run the program it doesn't seem to give any errors. Running the program should print out the existing text (displayContent), which is done after appending (addLine). But when I run it, it only shows the existing text, without the appended line.
It doesn't show up in the text file either. I tried to put a System.out.println(); in the method, and it prints, so I know its running the method properly, just not appending.
EDIT AWNSER: replaced f.getName() with f, and added pw.flush before pw.close()
I think that your displayContent(File) function has bugs.
The above code does append to the file.
Have a look at the file to see if anything is appended.
Also do you need to create PrintWriter object each time you append a line?
If there are many continuous lines to be appended, try using a single PrintWriter/ BufferedWriter object by creating a static/final object.

Buffered Writer overwriting file when not wanted

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

Is my write text to file wrong?

I have a file call "CI.txt"
Inside the file the information is:
Mr Abc;ABC;abc123;Abc Road;428428;VISA;2222111144442222
Mr Efg;EFG;efg123;Efg Road;424213;MASTERCARD;4444555566667777
Mr Lmn;LMN;lmn123;Lmn Road;492482;VISA;9999000011112222
Here is my code, it works very well but the problem is..
for (Customer ci : custList){
//Compares the username and userpassword
//If correct, set new card number and card type..
if (inputUser.equals(ci.getUserName()) && inputPass.equals(ci.getPassword())) {
ci.setCardNo(newCardNo);
ci.setCardType(newCardType);
}
String text = ci.getRealName() + ";" + ci.getUserName() + ";" + ci.getPassword() + ";" + ci.getContact() + ";" + ci.getcardType() + ";" + ci.getcardNo();
try {
File fileCI = new File("CI.txt");
FileWriter fileWriter = new FileWriter(fileCI);
BufferedWriter bw = new BufferedWriter(fileWriter);
bw.write(text);
bw.close();
}
catch (FileNotFoundException e) {
System.out.println("File not found");
}
catch (IOException e) {
System.out.println("Unable to write to file");
}
}
My output will only have the records of Mr Lmn. There is no record of Mr Abc whom I updated the new credit card type and number. Why is this happening? I did System.out.println(text) in the try statement and all was printed out properly. Anyone can help?
You are opening and closing the file in each iteration of the for-loop. Opening a file by default erases everything in it. You must open the file before starting the for-loop, and close it only afterwards.
The problem in your code that each for-loop iteration recreates the file and overwrites its content
You are building the Text and creating new file for each customer, so the last one override all the others:
for (Customer ci : custList){
//...
String text = ci.getRealName() + ";" + ci.getUserName() + ";" + ci.getPassword() + ";" + ci.getContact() + ";" + ci.getcardType() + ";" + ci.getcardNo();
try {
File fileCI = new File("CI.txt");
FileWriter fileWriter = new FileWriter(fileCI);
//...
}
You need to create the file outside the loop, then build the content and fill the file with data, and finally close the file.
The problem is that you are writing to the file inside the for loop. This means that with each loop, the file is overwritten with new data. In the end, only the last data is shown. You need to move the for-loop code inside the file-writing code, like this:
try
{
File fileCI = new File ( "CI.txt" );
FileWriter fileWriter = new FileWriter ( fileCI );
BufferedWriter bw = new BufferedWriter ( fileWriter );
for ( Customer ci : custList )
{
if ( inputUser.equals ( ci.getUserName () )
&& inputPass.equals ( ci.getPassword () ) )
{
ci.setCardNo ( newCardNo );
ci.setCardType ( newCardType );
}
String text = ci.getRealName () + ";" + ci.getUserName () + ";"
+ ci.getPassword () + ";" + ci.getContact () + ";"
+ ci.getcardType () + ";" + ci.getcardNo ();
bw.write ( text );
}
bw.close ();
fileWriter.close();
}
catch ( FileNotFoundException e )
{
System.out.println ( "File not found" );
}
catch ( IOException e )
{
System.out.println ( "Unable to write to file" );
}
You are running each customer in a loop.
for (Customer ci : custList){
Each time you run the loop, you create a new file called CI.txt
File fileCI = new File("CI.txt");
Since you create the file from scratch for every customer, only the last customer will remain. Open the file for append instead.
Use :
public FileWriter(File file,boolean append)
throws IOException
It says , append - if true, then bytes will be written to the end of the file rather than the beginning
Here is the API doc.

Categories

Resources