gpt4 book ai didi

java - 用Java读取文件

转载 作者:行者123 更新时间:2023-12-02 00:39:03 26 4
gpt4 key购买 nike

我有以下代码来打开和读取文件。我无法弄清楚如何让它通过并打印文件中每个字符的总数,打印第一个和最后一个字符,以及准确地在文件中间打印该字符。最有效的方法是什么?

这是主类:

import java.io.IOException;

public class fileData {

public static void main(String[ ] args) throws IOException {
String file_name = "/Users/JDB/NetBeansProjects/Program/src/1200.dna";

try {
ReadFile file = new ReadFile(file_name);
String[] arrayLines = file.OpenFile();

int i;
for (i=0; i<arrayLines.length; i++)
{
System.out.println(arrayLines[i]);
}
}

catch (IOException e) {
System.out.println(e.getMessage()) ;
}

}


}

和另一个类:

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


public class ReadFile {

private String path;

public ReadFile (String file_path)
{
path = file_path;
}

public String[] OpenFile() throws IOException
{
FileReader fr = new FileReader(path);
BufferedReader textReader = new BufferedReader(fr);

int numberOfLines = readLines();
String[] textData = new String[numberOfLines];

int i;

for(i=0; i<numberOfLines; i++)
{
textData[i] = textReader.readLine();
}

textReader.close();
return textData;
}

int readLines() throws IOException
{
FileReader file_to_read = new FileReader(path);
BufferedReader bf = new BufferedReader(file_to_read);

String aLine;
int numberOfLines = 0;

while (( aLine = bf.readLine() ) != null)
{
numberOfLines++;
}

bf.close();
return numberOfLines;
}

最佳答案

一些可能有帮助的提示。

  1. Map 可用于存储字母表中每个字符的信息。
  2. 从文件的大小可以找到文件的中间位置。

关于java - 用Java读取文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6893668/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com