Java 从 .dat 文件中读取信息
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18815739/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java Reading in Info from .dat Files
提问by Zeldarulah
Its been a few years since I've input .dat
files into a Java
program, and now I need to for this project. I remember back then I used the Scanner
class, but looking through the internet for solutions, it seems like there's a lot of options; things like BufferedReader
and FileStream
classes that I've never used before, or at least don't remember using.. Anyway, my question is:
自从我将.dat
文件输入到Java
程序中已经有几年了,现在我需要为这个项目输入文件。我记得当时我用过这Scanner
门课,但通过互联网寻找解决方案,似乎有很多选择;我以前从未使用过的类BufferedReader
和FileStream
类,或者至少不记得使用过..无论如何,我的问题是:
If I'm reading in .dat files of the format:
如果我正在阅读以下格式的 .dat 文件:
998763264 EGCDGHIJJ
697724736 GDHECHHJG
etc.
What class(es)
would you recommend I implement to handle this input? / Can you give me an example of said class being used to read in a file?
class(es)
您建议我实施什么来处理此输入?/ 你能举个例子说明这个类被用来读入文件吗?
Thanks a lot for the help.
非常感谢您的帮助。
采纳答案by Archer
If your .dat file is a text file which contains patterns you provided, Scanner seems is a good solution for you.
如果您的 .dat 文件是包含您提供的模式的文本文件,则 Scanner 似乎是您的一个不错的解决方案。
Try this code:
试试这个代码:
Scanner sc = new Scanner(new File("test.dat"));
Pattern p = Pattern.compile("([\w\d]*)\s*");
while (sc.findWithinHorizon(p, 0) != null)
{
MatchResult m = sc.match();
System.out.println(m.group(1));
}
回答by ASBH
I could suggest using the FileInputStream and an InputStreamReader.
我可以建议使用 FileInputStream 和 InputStreamReader。
You can find an usage example in this tutorial: http://tutorials.jenkov.com/java-io/inputstreamreader.html
您可以在本教程中找到使用示例:http: //tutorials.jenkov.com/java-io/inputstreamreader.html
In your example, you could use the reader.read(char[] cbuf, int off, int len) method to specifically read the desired chunks of characters.
在您的示例中,您可以使用 reader.read(char[] cbuf, int off, int len) 方法专门读取所需的字符块。