Search code examples
javaio

Read and Write from files Java


How can i read a number, string or a character from file. I find many ways but i don't know how is the best and clear approach. I want to make input/output operations like the System console.

I created 2 files input.in and output.out and I want to read a number from input.in and and print the number into output.out.

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

public class MainClass {

    public static void main(String[] args) throws IOException {
        File file = new File("input.in");
        Scanner scanner = new Scanner(file);
        String a = scanner.nextLine();
        System.out.println(a);
    }
}

I first want to test if is working to read from file but i got this :

Exception in thread "main" java.util.NoSuchElementException: No line found
  at java.util.Scanner.nextLine(Unknown Source)
  at MainClass.main(MainClass.java:9)

In the the file input.in i have :

file

i/o


Solution

  • You can use FileInputStream and FileOutputStream to do so..

    Hope this will serve your purpose

    import java.util.Scanner;
    import java.io.*;
    
    public class MainClass {
    
        public static void main(String[] args) throws IOException {
            FileInputStream inputStream = null;
            FileOutputStream outputStream = null;
            Scanner sc = null;
            try {
                inputStream = new FileInputStream("IN File");
                outputStream = new FileOutputStream("OUT File");
                sc = new Scanner(inputStream, "UTF-8");
                while (sc.hasNextLine()) {
                    String line = sc.nextLine();
                    System.out.println(line);
                    byte[] strToBytes = line.getBytes();
                    outputStream.write(strToBytes);
                    outputStream.write(System.getProperty("line.separator").getBytes());
                }
                // note that Scanner suppresses exceptions
                if (sc.ioException() != null) {
                    throw sc.ioException();
                }
            } catch (FileNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } finally {
                if (inputStream != null) {
                    inputStream.close();
                }
                if (sc != null) {
                    sc.close();
                }
            }
        }
    }