gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 17:54:12 26 4
gpt4 key购买 nike

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

最佳答案

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

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

与输出流相同Files.newOutputStream()

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

一般来说,这里是official tutorial from Oracle使用 IO。

关于来自文件路径的 Java 输入和输出流,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46723980/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com