Frage

I wrote a very simple piece of code, It was working perfectly since yesterday but now not working and even after lots of research/debugging i have not got the issue

 import java.net.InetAddress;
 import java.util.Date;
 import java.io.File;
 import java.io.FileWriter;
 import java.io.BufferedWriter;

  public class DetectLoggedInUser{

  public static void returnUserName()
  {
   String computerName;
   try {


     File file =new File("d:\\TestFolder\\UsersloggedIn.txt");

        if(!file.exists()){
            file.createNewFile();
        }


            FileWriter fileWritter = new FileWriter(file.getName(),true);
                BufferedWriter bufferWritter = new BufferedWriter(fileWritter);
            String content= "\n UserName="+System.getProperty("user.name")+ " || Date and Time= "+new Date();
            bufferWritter.write(content);
            bufferWritter.close();

}

catch(Exception ex) {
ex.printStackTrace();
}
}

public static void main(String args[])
{
returnUserName();
}
}

Now file is created but nothing is being written in file

Is there anything wrong with this code(keeping in mind it was working since yesterday)?

War es hilfreich?

Lösung

Try this:

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.util.Date;

public class DetectLoggedInUser {

    public static void returnUserName() {
        try {
            File file = new File("d:\\TestFolder\\UsersloggedIn.txt");

            if (!file.exists()) {
                file.createNewFile();
            }

            FileWriter fileWritter = new FileWriter(file, true);
            BufferedWriter bufferWritter = new BufferedWriter(fileWritter);
            String content = "\n UserName=" + System.getProperty("user.name")
                    + " || Date and Time= " + new Date();
            bufferWritter.write(content);
            bufferWritter.close();

        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    public static void main(String args[]) {
        returnUserName();
    }
}

Andere Tipps

You can use

FileWriter fileWritter = new FileWriter(file.getAbsolutePath(), true);

Instead of file.getName() in your code.File.getName() method returns only the name of the file or directory,not the absolute path;

You don't need to check if the files exists or not, beside that it works fine for me.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top