How to write text to a file in Java?

1. Using PrintWriter
public class WriteFile {     public static void main(String[] args) {         String fileName = "D:\\temp.txt";         PrintWriter writer = null;         try {             //will replace existing file.             writer = new PrintWriter(fileName);             writer.println("This is first line.");             writer.println("This is second line");             writer.close();         } catch (FileNotFoundException e) {             //occurs when user does not have permission to create file.             e.printStackTrace();
        } finally {             if (writer != null) {                 writer.close();             }         }     } }


2. Using Files class (JDK 7+)
public class WriteFile {
    public static void main(String[] args) throws IOException {
        List<String> lines = Arrays.asList("Line One", "Line Two");
        Path file = Paths.get("D:\\test.txt");
        Files.write(file, lines, Charset.forName("UTF-8"));
    }
}

0 comments:

Post a Comment