在Java中,似乎有不同的方式来读取和写入文件数据。
我想从一个文件读取ASCII数据。可能的方式和它们的区别是什么?
在Java中,似乎有不同的方式来读取和写入文件数据。
我想从一个文件读取ASCII数据。可能的方式和它们的区别是什么?
当前回答
在Java中从文件中读取数据的最简单方法是使用file类读取文件,使用Scanner类读取文件的内容。
public static void main(String args[])throws Exception
{
File f = new File("input.txt");
takeInputIn2DArray(f);
}
public static void takeInputIn2DArray(File f) throws Exception
{
Scanner s = new Scanner(f);
int a[][] = new int[20][20];
for(int i=0; i<20; i++)
{
for(int j=0; j<20; j++)
{
a[i][j] = s.nextInt();
}
}
}
PS:别忘了导入java.util.*;扫描仪的工作。
其他回答
try (Stream<String> stream = Files.lines(Paths.get(String.valueOf(new File("yourFile.txt"))))) {
stream.forEach(System.out::println);
} catch (IOException e) {
e.printStackTrace();
}
新文件(< path_name >)
通过将给定的路径名字符串转换为抽象路径名来创建一个新的File实例。如果给定的字符串是空字符串,那么结果就是空的抽象路径名。 参数: pathname -路径名字符串 抛出: NullPointerException -如果路径名参数为空
文件。lines返回String流
Stream<String> Stream = Files.lines(路径。get(字符串。返回对象的值(新文件(“yourFile.txt”)))) 可以抛出nullpointerexction, FileNotFoundException,所以,保持它在尝试将照顾异常在运行时
stream.forEach(System.out::println);
这用于在控制台中迭代流和打印 如果您有不同的用例,您可以提供您的自定义函数来操作行流
在实践中,缓冲流类的性能要高得多,以至于NIO.2 API包含了专门返回这些流类的方法,部分原因是为了鼓励您始终在应用程序中使用缓冲流。
这里有一个例子:
Path path = Paths.get("/myfolder/myfile.ext");
try (BufferedReader reader = Files.newBufferedReader(path)) {
// Read from the stream
String currentLine = null;
while ((currentLine = reader.readLine()) != null)
//do your code here
} catch (IOException e) {
// Handle file I/O exception...
}
您可以替换此代码
BufferedReader reader = Files.newBufferedReader(path);
与
BufferedReader br = new BufferedReader(new FileReader("/myfolder/myfile.ext"));
我推荐这篇文章来学习Java NIO和IO的主要用途。
你可以使用readAllLines和join方法在一行中获取整个文件内容:
String str = String.join("\n",Files.readAllLines(Paths.get("e:\\text.txt")));
它默认使用UTF-8编码,可以正确读取ASCII数据。
你也可以使用readAllBytes:
String str = new String(Files.readAllBytes(Paths.get("e:\\text.txt")), StandardCharsets.UTF_8);
我认为readAllBytes更快更精确,因为它不会用\n替换新行,也不会用\r\n替换新行。哪一种合适取决于你的需要。
这可能不是问题的确切答案。这只是读取文件的另一种方式,其中不需要在Java代码中显式指定文件的路径,而是将其作为命令行参数读取。
使用以下代码,
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
public class InputReader{
public static void main(String[] args)throws IOException{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String s="";
while((s=br.readLine())!=null){
System.out.println(s);
}
}
}
只需继续运行它,使用:
java InputReader < input.txt
这将读取input.txt的内容并将其打印到控制台。
你也可以让System.out.println()通过命令行写入一个特定的文件,如下所示:
java InputReader < input.txt > output.txt
这将从input.txt读取并写入output.txt。
Cactoos提供了一个声明性的一行代码:
new TextOf(new File("a.txt")).asString();