Java读写txt文件

如题所述

Java读取文本文件的方法主要包括从指定位置文件中一行一行读取内容,并将每行存入List集合。这是代码示例:

public static List readInputByRow(String path) {
List list=new ArrayList();
File file=new File(path);
try {
FileInputStream fis = new FileInputStream(file);
InputStreamReader isr = new InputStreamReader(fis, "UTF-8");
BufferedReader reader = new BufferedReader(isr);
String tempstring="";
while((tempstring=reader.readLine())!=null) {
list.add(tempstring);
}
reader.close();
isr.close();
fis.close();
return list; }
catch (IOException e) {
e.printStackTrace();
return null; }
}

另一种方法是从指定位置文件中读取指定一行数据。代码如下:

public static String readInputByRow(String path,int num) {
File file=new File(path);
try {
FileInputStream fis = new FileInputStream(file);
InputStreamReader isr = new InputStreamReader(fis, "UTF-8");
BufferedReader reader = new BufferedReader(isr);
String tempstring="";
int line=1;
while((tempstring=reader.readLine())!=null) {
if(line==num){
break;
}
line++;
}
reader.close();
isr.close();
fis.close();
return tempstring;
}
catch (IOException e) {
e.printStackTrace();
return null;
}

这两种方法都涉及到文件的输入流处理,以及使用BufferedReader逐行读取文件内容。需要注意的是,错误处理部分会打印异常信息,并在发生异常时返回null。

在实际应用中,这些方法可以灵活运用,根据需求读取文件的不同部分。同时,为了提高效率和代码的可维护性,建议对输入参数进行适当的校验和异常处理。

此外,还可以考虑使用try-with-resources语句来自动关闭资源,简化代码并提高可读性。例如:

public static List readInputByRow(String path) {
List list=new ArrayList();
File file=new File(path);
try (FileInputStream fis = new FileInputStream(file);
InputStreamReader isr = new InputStreamReader(fis, "UTF-8");
BufferedReader reader = new BufferedReader(isr)) {
String tempstring="";
while((tempstring=reader.readLine())!=null) {
list.add(tempstring);
}
return list;
} catch (IOException e) {
e.printStackTrace();
return null;
}

这种方式不仅简化了代码,还能确保资源被正确关闭。
温馨提示:答案为网友推荐,仅供参考
相似回答
大家正在搜