2018년 3월 19일 월요일

[Java] File Write Examples (String to File Write in Java)


1. String to File Examples


1) String write with BufferedWriter

1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
public static void main(String[] args) {
    try {
        String fileName = "d:/target.txt";
        String text = "Please write me to file";
        BufferedWriter writer = new BufferedWriter( new FileWriter( fileName));
        writer.write( text);
        writer.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}


2) String write with BufferedWriter (UTF-8)


1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
public static void main(String[] args) {
    try {
        String fileName = "d:/target.txt";
        String text = "Please write me to file";
        BufferedWriter writer new BufferedWriter(new OutputStreamWriter(new FileOutputStream(new File(fileName)),"UTF8"));
        writer.write( text);
        writer.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}



3) String write with FileWriter

1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
public static void main(String[] args) {
    try {
        String fileName = "d:/target.txt";
        String text = "Please write me to file";
        FileWriter fw = new FileWriter(new File(fileName));
        fw.write(text);
        fw.close();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}


4) String write with PrintStream

1
 2
 3
 4
 5
 6
 7
 8
 9
10
public static void main(String[] args) {
    try {
        String fileName = "d:/target.txt";
        String text = "Please write me to file";
        PrintStream out = new PrintStream(new FileOutputStream(fileName));
        out.print(text);
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }
}


5) String write with PrintWriter

1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
public static void main(String[] args) {
    try {
        String fileName = "d:/target.txt";
        String text = "Please write me to file";
        PrintWriter out = new PrintWriter(fileName);
        out.println(text);
        out.close();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }
}


6) String List to File 


1
2
3
void writeStringListToFile(String filename, List<String> lines) throws IOException {
    Files.write( Paths.get(filename), lines, StandardOpenOption.CREATE );
}



댓글 없음:

댓글 쓰기