[英]How i can read the hole Text File?
我正在使用这种方法从文本文件中读取所有文本行。 但该方法仅读取第一行。 请有任何想法!
我正在使用 Java API 方法Files.readAllLines()
public static String dateiEinlesen(String path, String name)
{
Path path = Paths.get(path, name);
Charset charset = Charset.forName("UTF-8");
try
{
List<String> lines = Files.readAllLines(path, charset);
for (String line : lines)
{
return line;
}
}
catch (IOException e)
{
}
return "File could not found! ";
}
问题是您从 for 循环返回,这意味着在读取第一行后退出该方法。 如果您打印出该行而不是返回它应该打印文件中的所有行。
如果您打算返回文件的所有行,那么只需将代码更改为:-
public static List<String> dateiEinlesen(String path, String name) throws IOException
{
Path filepath = Paths.get(path, name);
return Files.readAllLines(filepath, Charset.forName("UTF-8"));
}
捕获异常并且什么都不做是不常见的,因此最好让异常传播并让调用者处理它。
试试这个,只是改变路径
Path path = Paths.get("C:\\Users\\123\\Desktop\\", "write a patch.txt");
Charset charset = Charset.forName("UTF-8");
try
{
List<String> lines = Files.readAllLines(path, charset);
for (String line : lines)
{
System.out.println(line);
}
}
catch (IOException e)
{
}
}
你可以做什么而不是System out,你可以将行String存储在一个字符串数组中,然后在读完后显示所有内容
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.