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