【问题标题】:Java input and output stream from file path来自文件路径的 Java 输入和输出流
【发布时间】:2017-10-13 06:45:20
【问题描述】:

如何使用指定的文件路径而不是资源文件夹中的文件作为输入或输出流?这是我拥有的类,我想从特定的文件路径中读取,而不是将 txt 文件放在 IntelliJ 的资源文件夹中。对于输出流也是如此。感谢您提供任何帮助。

输入流

import java.io.*;
import java.util.*;

public class Example02 {
    public static void main(String[] args) throws FileNotFoundException {
        // STEP 1: obtain an input stream to the data

        // obtain a reference to resource compiled into the project
        InputStream is = Example02.class.getResourceAsStream("/file.txt");

        // convert to useful form
        Scanner in = new Scanner(is);

        // STEP 2: do something with the data stream
        // read contents
        while (in.hasNext()) {
            String line = in.nextLine();
            System.out.println(line);
        }

        // STEP 3: be polite, close the stream when done!
        // close file
        in.close();
    }
}

输出流

import java.io.*;

public class Example03
{
    public static void main(String []args) throws FileNotFoundException
    {
        // create/attach to file to write too
        // using the relative filename will cause it to create the file in
        // the PROJECT root
        File outFile = new File("info.txt");

        // convert to a more useful writer
        PrintWriter out = new PrintWriter(outFile);

        //write data to file
        for(int i=1; i<=10; i++)
            out.println("" + i + " x 5 = " + i*5);

        //close file - required!
        out.close();            
    }
}

【问题讨论】:

  • 文件输入流

标签: java inputstream


【解决方案1】:

获取 InputStream 的首选方式是java.nio.file.Files.newInputStream(Path)

try(final InputStream is = Files.newInputStream(Paths.get("/path/to/file")) {
    //Do something with is
}

同样适用于 OutputStream Files.newOutputStream()

try(final OutputStream os = Files.newOutputStream(Paths.get("/path/to/file")) {
    //Do something with os
}

一般来说,这里是official tutorial from Oracle 与 IO 合作。

【讨论】:

    【解决方案2】:

    首先您必须定义要从中读取文件的路径,绝对路径如下:

    String absolutePath = "C:/your-dir/yourfile.txt"
    InputStream is = new FileInputStream(absolutePath);
    

    写入文件也类似:

    String absolutePath = "C:/your-dir/yourfile.txt"
    PrintWriter out = new PrintWriter(new FileOutputStream(absolutePath));
    

    【讨论】:

      【解决方案3】:

      您可以将文件对象用作:

      File input = new File("C:\\[Path to file]\\file.txt");
      

      【讨论】:

        猜你喜欢
        • 2012-05-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-05-25
        • 2021-11-25
        • 2019-05-01
        • 1970-01-01
        相关资源
        最近更新 更多