用java读取纯文本文件

pbgvytdp  于 2021-07-06  发布在  Java
关注(0)|答案(28)|浏览(650)

在java中,似乎有不同的方法来读取和写入文件的数据。
我想从文件中读取ascii数据。可能的方法和它们的区别是什么?

lnlaulya

lnlaulya1#

这可能不是问题的确切答案。这只是另一种读取文件的方法,在这种方法中,您没有在java代码中显式指定文件的路径,而是将其作为命令行参数读取。
使用以下代码,

  1. import java.io.BufferedReader;
  2. import java.io.InputStreamReader;
  3. import java.io.IOException;
  4. public class InputReader{
  5. public static void main(String[] args)throws IOException{
  6. BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
  7. String s="";
  8. while((s=br.readLine())!=null){
  9. System.out.println(s);
  10. }
  11. }
  12. }

继续,用以下方法运行它:

  1. java InputReader < input.txt

这将读取 input.txt 然后打印到你的控制台上。
你也可以做你的 System.out.println() 通过命令行写入特定文件的步骤如下:

  1. java InputReader < input.txt > output.txt

这是从 input.txt 写信给 output.txt .

展开查看全部
mrfwxfqh

mrfwxfqh2#

  1. try {
  2. File f = new File("filename.txt");
  3. Scanner r = new Scanner(f);
  4. while (r.hasNextLine()) {
  5. String data = r.nextLine();
  6. JOptionPane.showMessageDialog(data);
  7. }
  8. r.close();
  9. } catch (FileNotFoundException ex) {
  10. JOptionPane.showMessageDialog("Error occurred");
  11. ex.printStackTrace();
  12. }
e4yzc0pl

e4yzc0pl3#

我编写的这段代码对于非常大的文件要快得多:

  1. public String readDoc(File f) {
  2. String text = "";
  3. int read, N = 1024 * 1024;
  4. char[] buffer = new char[N];
  5. try {
  6. FileReader fr = new FileReader(f);
  7. BufferedReader br = new BufferedReader(fr);
  8. while(true) {
  9. read = br.read(buffer, 0, N);
  10. text += new String(buffer, 0, read);
  11. if(read < N) {
  12. break;
  13. }
  14. }
  15. } catch(Exception ex) {
  16. ex.printStackTrace();
  17. }
  18. return text;
  19. }
展开查看全部
bfnvny8b

bfnvny8b4#

对于基于jsf的maven web应用程序,只需使用classloader和 Resources 要在任何文件中读取的文件夹:
将要读取的任何文件放在resources文件夹中。
将apache commons io依赖项放入pom:

  1. <dependency>
  2. <groupId>org.apache.commons</groupId>
  3. <artifactId>commons-io</artifactId>
  4. <version>1.3.2</version>
  5. </dependency>

使用下面的代码读取它(例如,下面是在.json文件中读取的):

  1. String metadata = null;
  2. FileInputStream inputStream;
  3. try {
  4. ClassLoader loader = Thread.currentThread().getContextClassLoader();
  5. inputStream = (FileInputStream) loader
  6. .getResourceAsStream("/metadata.json");
  7. metadata = IOUtils.toString(inputStream);
  8. inputStream.close();
  9. }
  10. catch (FileNotFoundException e) {
  11. // TODO Auto-generated catch block
  12. e.printStackTrace();
  13. }
  14. catch (IOException e) {
  15. // TODO Auto-generated catch block
  16. e.printStackTrace();
  17. }
  18. return metadata;

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

展开查看全部
tsm1rwdh

tsm1rwdh5#

ascii是一个文本文件,因此您可以使用 Readers 为了阅读。java还支持使用 InputStreams . 如果正在读取的文件很大,那么您应该使用 BufferedReader 在树顶上 FileReader 以提高读取性能。
通读这篇关于如何使用 Reader 我还建议您下载并阅读这本名为《java思考》的精彩(免费)书籍
在java 7中:

  1. new String(Files.readAllBytes(...))

(文件)或

  1. Files.readAllLines(...)

(文档)
在java 8中:

  1. Files.lines(..).forEach(...)

(文档)

展开查看全部
rdlzhqv9

rdlzhqv96#

Guava提供了一个班轮:

  1. import com.google.common.base.Charsets;
  2. import com.google.common.io.Files;
  3. String contents = Files.toString(filePath, Charsets.UTF_8);
gcmastyq

gcmastyq7#

你想怎么处理这篇课文?这个文件小到可以放入内存吗?我会尽量找到最简单的方法来处理您的需要的文件。fileutils库非常适合处理这个问题。

  1. for(String line: FileUtils.readLines("my-text-file"))
  2. System.out.println(line);
z5btuh9x

z5btuh9x8#

到目前为止,我还没有看到其他答案中提到这一点。但是,如果“best”意味着速度,那么新的javai/o(nio)可能会提供最快的性能,但对于学习的人来说并不总是最容易理解的。
http://download.oracle.com/javase/tutorial/essential/io/file.html

jjhzyzn0

jjhzyzn09#

  1. String fileName = 'yourFileFullNameWithPath';
  2. File file = new File(fileName); // Creates a new file object for your file
  3. FileReader fr = new FileReader(file);// Creates a Reader that you can use to read the contents of a file read your file
  4. BufferedReader br = new BufferedReader(fr); //Reads text from a character-input stream, buffering characters so as to provide for the efficient reading of characters, arrays, and lines.

上述行可以写成一行:

  1. BufferedReader br = new BufferedReader(new FileReader("file.txt")); // Optional

添加到字符串生成器(如果文件很大,建议使用字符串生成器,否则使用普通字符串对象)

  1. try {
  2. StringBuilder sb = new StringBuilder();
  3. String line = br.readLine();
  4. while (line != null) {
  5. sb.append(line);
  6. sb.append(System.lineSeparator());
  7. line = br.readLine();
  8. }
  9. String everything = sb.toString();
  10. } finally {
  11. br.close();
  12. }
展开查看全部
vq8itlhq

vq8itlhq10#

其中的方法 org.apache.commons.io.FileUtils 也可能非常方便,例如:

  1. /**
  2. * Reads the contents of a file line by line to a List
  3. * of Strings using the default encoding for the VM.
  4. */
  5. static List readLines(File file)
lkaoscv7

lkaoscv711#

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

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

它默认使用utf-8编码,可以正确读取ascii数据。
您还可以使用readallbytes:

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

我认为readallbytes更快更精确,因为它不会将新行替换为 \n 也可能是新的路线 \r\n . 这取决于你的需要哪一个合适。

ou6hu8tu

ou6hu8tu12#

这基本上与jesus ramos的答案完全相同,只是使用file而不是filereader,再加上逐步遍历文件内容的迭代。

  1. Scanner in = new Scanner(new File("filename.txt"));
  2. while (in.hasNext()) { // Iterates each line in the file
  3. String line = in.nextLine();
  4. // Do something with line
  5. }
  6. in.close(); // Don't forget to close resource leaks

... 投掷 FileNotFoundException

hzbexzde

hzbexzde13#

缓冲流类在实践中的性能要高得多,以至于nio.2api包含了专门返回这些流类的方法,部分原因是为了鼓励您在应用程序中始终使用缓冲流。
举个例子:

  1. Path path = Paths.get("/myfolder/myfile.ext");
  2. try (BufferedReader reader = Files.newBufferedReader(path)) {
  3. // Read from the stream
  4. String currentLine = null;
  5. while ((currentLine = reader.readLine()) != null)
  6. //do your code here
  7. } catch (IOException e) {
  8. // Handle file I/O exception...
  9. }

您可以替换此代码

  1. BufferedReader reader = Files.newBufferedReader(path);

  1. BufferedReader br = new BufferedReader(new FileReader("/myfolder/myfile.ext"));

我推荐本文来学习javanio和io的主要用法。

展开查看全部
dm7nw8vv

dm7nw8vv14#

我在java中记录了15种读取文件的方法,然后用不同的文件大小测试了它们的速度—从1 kb到1 gb和以下三种方法: java.nio.file.Files.readAllBytes() 在Java7、8和9中进行了测试。

  1. import java.io.File;
  2. import java.io.IOException;
  3. import java.nio.file.Files;
  4. public class ReadFile_Files_ReadAllBytes {
  5. public static void main(String [] pArgs) throws IOException {
  6. String fileName = "c:\\temp\\sample-10KB.txt";
  7. File file = new File(fileName);
  8. byte [] fileBytes = Files.readAllBytes(file.toPath());
  9. char singleChar;
  10. for(byte b : fileBytes) {
  11. singleChar = (char) b;
  12. System.out.print(singleChar);
  13. }
  14. }
  15. }
  16. ``` `java.io.BufferedReader.readLine()` 在Java7,8,9中进行了测试。

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class ReadFile_BufferedReader_ReadLine {
public static void main(String [] args) throws IOException {
String fileName = "c:\temp\sample-10KB.txt";
FileReader fileReader = new FileReader(fileName);

  1. try (BufferedReader bufferedReader = new BufferedReader(fileReader)) {
  2. String line;
  3. while((line = bufferedReader.readLine()) != null) {
  4. System.out.println(line);
  5. }
  6. }

}
}
``` java.nio.file.Files.lines() 这在Java8和Java9中测试过,但由于lambda表达式的要求,在Java7中不起作用。

  1. import java.io.File;
  2. import java.io.IOException;
  3. import java.nio.file.Files;
  4. import java.util.stream.Stream;
  5. public class ReadFile_Files_Lines {
  6. public static void main(String[] pArgs) throws IOException {
  7. String fileName = "c:\\temp\\sample-10KB.txt";
  8. File file = new File(fileName);
  9. try (Stream linesStream = Files.lines(file.toPath())) {
  10. linesStream.forEach(line -> {
  11. System.out.println(line);
  12. });
  13. }
  14. }
  15. }
展开查看全部
q9yhzks0

q9yhzks015#

可能没有缓冲i/o那么快,但非常简洁:

  1. String content;
  2. try (Scanner scanner = new Scanner(textFile).useDelimiter("\\Z")) {
  3. content = scanner.next();
  4. }

这个 \Z 图案告诉我们 Scanner 分隔符是eof。

相关问题