Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Java写文件方式 #31

Open
strongant opened this issue Mar 30, 2017 · 0 comments
Open

Java写文件方式 #31

strongant opened this issue Mar 30, 2017 · 0 comments

Comments

@strongant
Copy link
Owner

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.List;

/**
 * Created by strongant on 2017/3/30.
 */
public class WriteFile {

    private static final String filename = "writer.txt";

    //classic
    public static void writeTextFile() {
        try {
            PrintWriter writer = new PrintWriter("write.txt", "UTF-8");
            writer.println("The first line");
            writer.println("The second line");
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //classic
    public static void writeBinaryFile() {
        try {
            byte data[] = {};
            FileOutputStream writer = new FileOutputStream("write.mp3");
            writer.write(data);
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //jdk7+
    public static void writeTextFileByJDK7() {
        List<String> lines = Arrays.asList("The first line", "The second line");
        Path file = Paths.get("writer7.txt");
        try {
            Files.write(file, lines, Charset.forName("UTF-8"));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void writeBinaryFileByJDK7() {
        byte data[] = {};
        Path file = Paths.get("writer7.mp3");
        try {
            Files.write(file, data);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    public static void main(String[] args) {
        writeTextFile();
    }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant