简体   繁体   中英

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

Like RealSkeptic mentioned in the comments, I suspect your application fails to find the file you have provided. I suggest you adopt the following code:

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

public class MainClass {
    public static void main(String[] args) throws Exception {
        String filePath = "c:\\absolute\\path\\to\\input.in";
        File file = new File(filePath);
        if(file.exists()) {
            System.out.println("Reading contents of file at: " + filePath)
            try (Scanner scanner = new Scanner(file)) {
                while(scanner.hasNext()) {
                    String a = scanner.nextLine();
                    System.out.println(a);
                }
            }
        }
        else {
            System.out.println("File not found at: " + filePath);
        }
    }
}

References:

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

The path was wrong. For those who also have my problem here is the code for input/output operations:

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

public class MainClass {

    public static void main(String[] args) throws IOException {
        //the root path is your project name
        File in = new File("input.in");
        File out = new File("output.out");

        Scanner scannerInput = new Scanner(in);
        BufferedWriter writer = new BufferedWriter(new FileWriter(out));
        String string;
        while(scannerInput.hasNextLine()) {
            string = scannerInput.nextLine();
            writer.write(string);
            writer.newLine();
        }

        writer.flush();//very important
        scannerInput.close();
        writer.close();

    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM