简体   繁体   English

从文件读取和写入Java

[英]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. 我创建了2个文件input.in和output.out,我想从input.in中读取一个数字并将其打印到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 : 在文件input.in中,我有:

file 文件

i/o 输入/输出

Like RealSkeptic mentioned in the comments, I suspect your application fails to find the file you have provided. 就像注释中提到的RealSkeptic一样,我怀疑您的应用程序无法找到您提供的文件。 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.. 您可以使用FileInputStreamFileOutputStream来这样做。

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

    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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