如何使用指定的文件路徑而不是資源文件夾中的文件作爲輸入或輸出流?這是我有的類,我想從特定的文件路徑中讀取,而不是將txt文件放在IntelliJ中的資源文件夾中。輸出流相同。任何幫助呈現將不勝感激謝謝。來自文件路徑的Java輸入和輸出流
輸入流
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();
}
}
FileInputStream – GurV