0

I'm curious that the location where java.io.PrintWriter creates the file is always in the root directory of my project, I want the generated file to be in my current java module, do I need to specify the absolute path to the file location? Or is it related to the settings of my IDEA? Here is the code:

    package com.study.inputandoutput.textFile;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.nio.charset.StandardCharsets;
import java.time.LocalDate;
import java.util.Scanner;

public class TextFileTest {
    public static void main(String[] args) throws IOException {
        Employee[] staff = new Employee[3];

        staff[0] = new Employee("Marry", 75000, 1993, 8, 22);
        staff[1] = new Employee("Jerry", 50000, 1997, 1, 22);
        staff[2] = new Employee("Harry", 40000, 1996, 7, 17);

        //save all employee records to the file employee.dat
        try (PrintWriter out = new PrintWriter("employee.dat", StandardCharsets.UTF_8)){
            writeData(staff, out);
        }
    }

    /**
     * Write all employees in an array to a print writer.
     * @param employees an array of employees
     * @param out a print writer
     */
    private static void writeData(Employee[] employees, PrintWriter out) {
        //write number of employee
        out.println(employees.length);

        //write every employee
        for (Employee e : employees) {
            writeEmployee(out, e);
        }
    }

    /**
     * Write employee data to a print writer
     * @param out the print writer
     * @param e an employee of employees arrays
     */
    private static void writeEmployee(PrintWriter out, Employee e) {
        out.println(e.getName() + "|" + e.getSalary() + "|" + e.getHireDay());
    }
}
John Kugelman
  • 349,597
  • 67
  • 533
  • 578
  • The real question should be "_can I change the location of the file?_" The answer to that question is **_yes_**. Here is how: https://stackoverflow.com/questions/5797208/java-how-do-i-write-a-file-to-a-specified-directory – hfontanez Jan 14 '22 at 15:52
  • If you specify a relative path, the location of the output file will depend on where you run the program from. How are you running your program? And where would you like the file to be placed, relative to where you're running the code from? – byxor Jan 14 '22 at 15:55

0 Answers0