读取 java 中的文件

Read file in java

我的电脑中有一个扩展名为 .file 的文件,我想以 9 个字符×9 个字符的形式读取它。我知道我可以通过这段代码读取文件,但是我的文件不是.txt怎么办?java支持用这段代码读取.file吗?

                InputStream is = null;
                InputStreamReader isr = null;
                BufferedReader br = null;
                is = new FileInputStream("c:/test.txt");
                // create new input stream reader
                isr = new InputStreamReader(is);
                // create new buffered reader
                br = new BufferedReader(isr);
                // creates buffer
                char[] cbuf = new char[is.available()];
                for (int i = 0; i < 90000000; i += 9) {
                // reads characters to buffer, offset i, len 9
                br.read(cbuf, i, 9);}

does java support to read .file s with this code?

不,因为 c:/test.txt 是硬编码的。不会的话支持一下。

是的,如果你写 is = new FileInputStream("c:/test.file");

是可能的

是的,它会以相同的方式读取您提供给它的任何文件。您可以将具有任何扩展名的任何文件路径传递给 FileInputStream 构造函数。

文件的扩展名完全无关紧要。 .txt 等扩展名只是约定俗成,可帮助您的操作系统在您打开程序时选择正确的程序。

因此您可以将文本存储在任何文件中(.txt.file.foobar 如果您愿意...),前提是 知道它包含什么样的数据,并相应地从你的程序中读取它。

是的,Java 可以读取 .file 个文件,如果该文件包含文本,您的代码将正常工作。

任何人都可以阅读您想要的任何文件,因为文件只是一个字节序列。扩展名告诉您应以何种格式读取字节,因此当我们有一个 .txt 文件时,我们知道这是一个包含字符序列的文件。

当您有一个名为 .file 的文件格式时,我们知道它应该是(根据您的)9x9 字符集。这样我们就知道该读什么,该怎么做。

因为 .file 格式是字符,我会说是的,你可以用你的代码阅读它,例如:

public String[] readFileFormat (final File file) throws IOException {
    if (file.exists()) {
        final String[] lines = new String[9];
        final BufferedReader reader = new BufferedReader ( new FileReader( file ) );
        for ( int i = 0; i < lines.length; i++ ) {
            lines[i] = reader.readLine();
            if (lines[i] == null || lines[i].isEmpty() || lines[i].length() < 9)
                throw new RuntimeException ("Line is empty when it should be filled!");
            else if (lines[i].length() > 9)
                throw new RuntimeException ("Line does not have exactly 9 characters!");
        }
        reader.close();
        return lines;
    }
    return null;
}

扩展名完全无关紧要,因此它可以是 .file、.txt 或您想要的任何名称。

下面是一个使用 BuffereInputStream 读取 .file 类型文件的示例。这是讨论 15 ways to read files in Java.

的更大指南的一部分
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

public class ReadFile_BufferedInputStream_Read {
  public static void main(String [] pArgs) throws FileNotFoundException, IOException {
    String fileName = "c:\temp\sample-10KB.file";
    File file = new File(fileName);
    FileInputStream fileInputStream = new FileInputStream(file);

    try (BufferedInputStream bufferedInputStream = new BufferedInputStream(fileInputStream)) {
      int singleCharInt;
      char singleChar;
      while((singleCharInt = bufferedInputStream.read()) != -1) {
        singleChar = (char) singleCharInt;
        System.out.print(singleChar);
      }
    }
  }
}