Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java input and output stream from file path

How does one use a specified file path rather than a file from the resource folder as an input or output stream? This is the class I have and I would like to read from a specific file path instead of placing the txt file in the resources folder in IntelliJ. Same for an output stream. Any help rendered would be appreciated thanks.

Input Stream

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

Output stream

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();            
    }
}
like image 735
Torque Avatar asked Oct 13 '17 06:10

Torque


People also ask

What are the file streams for input and output in java?

The InputStream is used to read data from a source and the OutputStream is used for writing data to a destination. Here is a hierarchy of classes to deal with Input and Output streams. The two important streams are FileInputStream and FileOutputStream, which would be discussed in this tutorial.

How do I get the InputStream path?

InputStream realData = getClass(). getClassLoader(). getResourceAsStream("testfile. xml");


1 Answers

Preferred way for getting InputStream is java.nio.file.Files.newInputStream(Path)

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

Same for OutputStream Files.newOutputStream()

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

Generally, here is official tutorial from Oracle to working with IO.

like image 84
rkosegi Avatar answered Oct 28 '22 21:10

rkosegi