1

how can i create a new ".txt" file in java netbeans without overwriting the previous saved file?

here is my code, i used the method of setting a filename because i don't know yet how to create a new .txt file and not to overwrite the previous one

        File file = new File("Basic Student Information.txt");
    try {
        Files.write(Paths.get("Basic Student Information.txt"),list);
        Scanner scan = new Scanner(file);
        //while(scan.hasNext()){
        //    JOptionPane.showMessageDialog(null,scan.nextLine());
        //}
    } catch (IOException ex) {
        Logger.getLogger(StudentInfo.class.getName()).log(Level.SEVERE, null, ex);
    }
Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373
Ryu
  • 11
  • 3

4 Answers4

0

This is a HW program I guess, so I should not give you the exact code. But what you can do is to check if the file exists, if not then write to it else create a new file. Something like this :

File f = new File(filePathString);
if(f.exists() && !f.isDirectory()) { 
// do something
} else {
//create a new file and write to it
}
Pritam Banerjee
  • 17,953
  • 10
  • 93
  • 108
0

You can check if the file already exists:

File f = new File("name.txt");
if(f.exists() && !f.isDirectory()) { 
   // create file with other name
}else{
   // Use that filename
}

Is something like this that you want?

patricia
  • 1,075
  • 1
  • 16
  • 44
0

Instead of hardcoding the file name in the declaration,

File file = new File("Basic Student Information.txt");

try setting the file name as a variable itself

String fileName = "something.txt";
File file = new File(fileName);

And if your file would be overwritten, simply edit the string instead.

if(f.exists() && !f.isDirectory()) 
{ 
   fileName = "somethingelse.txt";
}
else
{
   // Use filename
}
//Name file as normal

If you will be doing this multiple times, you can even set up a for loop that adds the current iteration to the file name in order to dynamically generate new names.

Scott Forsythe
  • 360
  • 6
  • 18
0

Easiest way to create unique file names is to put the date and time in the file name. Like this.

Basic Student Information 2016/01/26 11:04:02.txt

And here's one way to do this:

package com.ggl.testing;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

public class CreateFileName {

    public static void main(String[] args) {
        CreateFileName createFileName = new CreateFileName();
        String fs = createFileName.createFileName("Basic Student Information",
                "txt");
        System.out.println(fs);
    }

    public String createFileName(String name, String extension) {
        DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
        Date currentDate = new Date();
        return name + " " + dateFormat.format(currentDate) + "." + extension;
    }

}
Gilbert Le Blanc
  • 50,182
  • 6
  • 67
  • 111