英文:
File Reader in Java
问题
In java: 我正在读取一个名为fn的文件。它是一个文本文件,第一个数字表示行数和字符数:
示例:
4
AFBA\n
BBBB\n
EFHE\n
EFJH\n
每4个字符后有一个换行符。这适用于4行。
我目前拥有的是:
File fp = new File(fn);
FileReader fr = new FileReader(fp);
BufferedReader bfr = new BufferedReader(fr);
我如何创建一个Java算法来将这些数据存储在数据结构中,如ArrayList、数组、堆栈等。
非常感谢。我刚刚开始编程,所以如果这个问题不符合Stack Overflow的规范,我很抱歉。
英文:
In java: I am reading a file named fn. It is a text file, and the first number gives the number of lines and characters:
Example:
4
AFBA\n
BBBB\n
EFHE\n
EFJH\n
Theres a new line after each 4 characters. This goes for 4 rows.
What I have so far is:
File fp = new File(fn);
FileReader fr = new FileReader(fp);
BufferedReader bfr = new BufferedReader(fr);
How do I create a java algorithm to store this data in a data structure, such as an array list, array, stack, etc.
Thanks so much. I'm just getting started programming so sorry if this question doesn't match the Stack overflow rhetoric.
答案1
得分: 2
你可以使用Java 8的Stream API和nio库将每一行存储为集合中的对象。例如:
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.stream.Stream;
import java.util.*;
public class streamFileRead {
public static void main(String args[]) {
String fileName = "drive://location//fn.txt";
List<String> list = new ArrayList<String>();
try (Stream<String> stream = Files.lines(Paths.get(fileName))) {
list = stream.collect(Collectors.toList());
} catch (IOException e) {
e.printStackTrace();
}
}
}
我保证这比使用循环逐行读取并使用\\n
来识别换行符要快得多且更可靠。
英文:
You can use Java 8 Stream API and nio library to store each line as an object in a collection. For example:
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.stream.Stream;
import java.util.*;
public class streamFileRead {
public static void main(String args[]) {
String fileName = "drive://location//fn.txt";
List<String> list = new ArrayList<String>();
try (Stream<String> stream = Files.lines(Paths.get(fileName))) {
list = stream.collect(Collectors.toList());
} catch (IOException e) {
e.printStackTrace();
}
}
}
I guarantee this is way more fast and foolproof than reading each line using a loop and identifying line breaks using \n
.
答案2
得分: 0
你可以尝试这样做:
class ReadFile{
public static void main(String[] args) throws IOException {
File fp = new File(fn);
FileReader fr = new FileReader(fp);
BufferedReader bfr = new BufferedReader(fr);
List<String> list = new ArrayList<>();
String s = "";
while ((s = bfr.readLine()) != null) {
list.add(s);
}
System.out.print(list);
}
}
英文:
You can try this :
class ReadFile{
public static void main(String[] args) throws IOException {
File fp = new File(fn);
FileReader fr = new FileReader(fp);
BufferedReader bfr = new BufferedReader(fr);
List<String> list= new ArrayList<>();
String s="";
while( (s=(bfr.readLine()))!=null){
list.add(s);
}
System.out.print(list);
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论