Thomas Breakell
Thomas Breakell

Reputation: 61

How to create a .txt file within the java project folder and write to it

I am attempting to create a text file within my project folder (not within the src but the System library). I have already created a print to display the proper info in the correct format. I copied and pasted this and edited the "System.out.println" to "PrintWriter.println". I am not sure if this code is correct although it shows no errors.

try {
        File file = new File("SortedLists.txt");
        FileWriter w = new FileWriter("SortedLists.txt");
        writer = new PrintWriter(w);

        for(Team p: roster){
            writer.println("Team Name: "+p.gettName()+", "+p.gettAbrv());
            for(Riders r: p.getRide()) {
                writer.println(r);
            }
            writer.printf("Total Team Donations: %.2f$\n",p.getSumD());
        }
    }
    catch(IOException e) {
        System.out.println(e.getMessage());
    }
    finally {
        writer.close();
    }

Upvotes: 1

Views: 9640

Answers (2)

Yahya
Yahya

Reputation: 14062

If you want to know where is your created file, you simply write for example

System.out.println(file.getAbsolutePath());

Furthermore, if you want to create a file in a relative path (say in a folder for example) you can do something like this:

File folder = new File("folderName"); 
folder.mkdir(); // create a folder in your current work space
File file = new File(folder, "fileName.txt"); // put the file inside the folder
file.createNewFile(); // create the file

Upvotes: 3

Benny Rubin
Benny Rubin

Reputation: 1

To set the path for the file create the file as follows:

String fileLocation = absolutePathToFile;

File file = new File(Location);

Upvotes: 0

Related Questions