有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!


共 (6) 个答案

  1. # 1 楼答案

    用Java创建和写入文件的一种非常简单的方法:

    import java.io.BufferedWriter;
    import java.io.File;
    import java.io.FileWriter;
    
    public class CreateFiles {
    
        public static void main(String[] args) {
            try{
                // Create new file
                String content = "This is the content to write into create file";
                String path="D:\\a\\hi.txt";
                File file = new File(path);
    
                // If file doesn't exists, then create it
                if (!file.exists()) {
                    file.createNewFile();
                }
    
                FileWriter fw = new FileWriter(file.getAbsoluteFile());
                BufferedWriter bw = new BufferedWriter(fw);
    
                // Write in file
                bw.write(content);
    
                // Close connection
                bw.close();
            }
            catch(Exception e){
                System.out.println(e);
            }
        }
    }
    
  2. # 2 楼答案

    在Java 7及更高版本中:

    try (Writer writer = new BufferedWriter(new OutputStreamWriter(
                  new FileOutputStream("filename.txt"), "utf-8"))) {
       writer.write("something");
    }
    

    不过,有一些有用的实用程序:

    • ^来自commons io的{a1}
    • ^来自番石榴的{a2}

    还请注意,您可以使用FileWriter,但它使用默认编码,这通常是个坏主意-最好显式指定编码

    下面是Java 7之前的原始答案


    Writer writer = null;
    
    try {
        writer = new BufferedWriter(new OutputStreamWriter(
              new FileOutputStream("filename.txt"), "utf-8"));
        writer.write("Something");
    } catch (IOException ex) {
        // Report
    } finally {
       try {writer.close();} catch (Exception ex) {/*ignore*/}
    }
    

    另见:Reading, Writing, and Creating Files(包括NIO2)

  3. # 3 楼答案

    如果您已经有了要写入文件的内容(并且不是动态生成的),那么Java 7中的^{}添加作为本机I/O的一部分提供了实现目标的最简单和最有效的方法

    基本上,创建和写入文件只需一行,而且一个简单的方法调用

    以下示例创建并写入6个不同的文件,以展示如何使用它:

    Charset utf8 = StandardCharsets.UTF_8;
    List<String> lines = Arrays.asList("1st line", "2nd line");
    byte[] data = {1, 2, 3, 4, 5};
    
    try {
        Files.write(Paths.get("file1.bin"), data);
        Files.write(Paths.get("file2.bin"), data,
                StandardOpenOption.CREATE, StandardOpenOption.APPEND);
        Files.write(Paths.get("file3.txt"), "content".getBytes());
        Files.write(Paths.get("file4.txt"), "content".getBytes(utf8));
        Files.write(Paths.get("file5.txt"), lines, utf8);
        Files.write(Paths.get("file6.txt"), lines, utf8,
                StandardOpenOption.CREATE, StandardOpenOption.APPEND);
    } catch (IOException e) {
        e.printStackTrace();
    }
    
  4. # 4 楼答案

    注意下面的每个代码示例都可能抛出IOException。为简洁起见,省略了Try/catch/finally块。有关异常处理的信息,请参见this tutorial

    注意,如果文件已经存在,下面的每个代码示例都将覆盖该文件

    创建文本文件:

    PrintWriter writer = new PrintWriter("the-file-name.txt", "UTF-8");
    writer.println("The first line");
    writer.println("The second line");
    writer.close();
    

    创建二进制文件:

    byte data[] = ...
    FileOutputStream out = new FileOutputStream("the-file-name");
    out.write(data);
    out.close();
    

    Java 7+用户可以使用^{}类写入文件:

    创建文本文件:

    List<String> lines = Arrays.asList("The first line", "The second line");
    Path file = Paths.get("the-file-name.txt");
    Files.write(file, lines, StandardCharsets.UTF_8);
    //Files.write(file, lines, StandardCharsets.UTF_8, StandardOpenOption.APPEND);
    

    创建二进制文件:

    byte data[] = ...
    Path file = Paths.get("the-file-name");
    Files.write(file, data);
    //Files.write(file, data, StandardOpenOption.APPEND);
    
  5. # 5 楼答案

    下面是一个创建或覆盖文件的小示例程序。这是一个很长的版本,因此更容易理解

    import java.io.BufferedWriter;
    import java.io.File;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.OutputStreamWriter;
    import java.io.Writer;
    
    public class writer {
        public void writing() {
            try {
                //Whatever the file path is.
                File statText = new File("E:/Java/Reference/bin/images/statsTest.txt");
                FileOutputStream is = new FileOutputStream(statText);
                OutputStreamWriter osw = new OutputStreamWriter(is);    
                Writer w = new BufferedWriter(osw);
                w.write("POTATO!!!");
                w.close();
            } catch (IOException e) {
                System.err.println("Problem writing to the file statsTest.txt");
            }
        }
    
        public static void main(String[]args) {
            writer write = new writer();
            write.writing();
        }
    }
    
  6. # 6 楼答案

    public class Program {
        public static void main(String[] args) {
            String text = "Hello world";
            BufferedWriter output = null;
            try {
                File file = new File("example.txt");
                output = new BufferedWriter(new FileWriter(file));
                output.write(text);
            } catch ( IOException e ) {
                e.printStackTrace();
            } finally {
              if ( output != null ) {
                output.close();
              }
            }
        }
    }