简体   繁体   中英

Writing in a text File in java

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)?

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();
    }
}

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;

你不需要检查文件是否存在,除此之外它对我来说很好。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM