在Java中,似乎有不同的方式来读取和写入文件数据。

我想从一个文件读取ASCII数据。可能的方式和它们的区别是什么?


当前回答

这可能不是问题的确切答案。这只是读取文件的另一种方式,其中不需要在Java代码中显式指定文件的路径,而是将其作为命令行参数读取。

使用以下代码,

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;

public class InputReader{

    public static void main(String[] args)throws IOException{
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        String s="";
        while((s=br.readLine())!=null){
            System.out.println(s);
        }
    }
}

只需继续运行它,使用:

java InputReader < input.txt

这将读取input.txt的内容并将其打印到控制台。

你也可以让System.out.println()通过命令行写入一个特定的文件,如下所示:

java InputReader < input.txt > output.txt

这将从input.txt读取并写入output.txt。

其他回答

你可以使用readAllLines和join方法在一行中获取整个文件内容:

String str = String.join("\n",Files.readAllLines(Paths.get("e:\\text.txt")));

它默认使用UTF-8编码,可以正确读取ASCII数据。

你也可以使用readAllBytes:

String str = new String(Files.readAllBytes(Paths.get("e:\\text.txt")), StandardCharsets.UTF_8);

我认为readAllBytes更快更精确,因为它不会用\n替换新行,也不会用\r\n替换新行。哪一种合适取决于你的需要。

Guava提供了一个简单的例子:

import com.google.common.base.Charsets;
import com.google.common.io.Files;

String contents = Files.toString(filePath, Charsets.UTF_8);

对于基于jsf的Maven web应用程序,只需使用ClassLoader和Resources文件夹读取任何你想要的文件:

Put any file you want to read in the Resources folder. Put the Apache Commons IO dependency into your POM: <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-io</artifactId> <version>1.3.2</version> </dependency> Use the code below to read it (e.g. below is reading in a .json file): String metadata = null; FileInputStream inputStream; try { ClassLoader loader = Thread.currentThread().getContextClassLoader(); inputStream = (FileInputStream) loader .getResourceAsStream("/metadata.json"); metadata = IOUtils.toString(inputStream); inputStream.close(); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return metadata;

您可以对文本文件、.properties文件、XSD模式等执行相同的操作。

到目前为止,我还没有在其他答案中看到它。但是如果“最佳”意味着速度,那么新的Java I/O (NIO)可能提供最快的性能,但对于初学者来说并不总是最容易理解的。

http://download.oracle.com/javase/tutorial/essential/io/file.html

下面是用Java 8的方式实现的一行程序。假设text.txt文件位于Eclipse项目目录的根目录中。

Files.lines(Paths.get("text.txt")).collect(Collectors.toList());