Java文件路径的输入和输出流

7

如何使用指定的文件路径而不是从资源文件夹中读取文件作为输入/输出流?这是我所拥有的类,我想从特定的文件路径读取,而不是将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();            
    }
}

2
FileInputStream - Gurwinder Singh
3个回答

19

获取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
}

一般来说,这里有来自 Oracle 的官方教程 IO的操作.


0

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

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));

-1

您可以将文件对象用作:

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接