如何通过java实现对指定目录下的txt文件进行增删改查?
1.如何删除该txt文件内指定行所有字符?2.如何以关键字搜索txt文件内内容并输出该关键字所在那一行的所有字符?很急,在线等,感谢...
1.如何删除该txt文件内指定行所有字符?
2.如何以关键字搜索txt文件内内容并输出该关键字所在那一行的所有字符?
很急,在线等,感谢 展开
2.如何以关键字搜索txt文件内内容并输出该关键字所在那一行的所有字符?
很急,在线等,感谢 展开
展开全部
代码如下:
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.List;
public class App61 {
public static void main(String[] args) throws IOException {
// 查找行输出
String line = findFileLine("mylist.txt", "abc");
System.out.println(line);
// 删除指定行
removeFileLine("mylist.txt", 2);
}
static void removeFileLine(String file, int line) throws IOException {
List<String> lines = readFileLines(file);
lines.remove(line - 1);
FileOutputStream outputStream = null;
OutputStreamWriter streamWriter = null;
BufferedWriter writer = null;
try {
outputStream = new FileOutputStream(file);
streamWriter = new OutputStreamWriter(outputStream);
writer = new BufferedWriter(streamWriter);
for (String str : lines) {
writer.write(str + System.lineSeparator());
}
} finally {
if (writer != null) {
writer.close();
}
if (streamWriter != null) {
streamWriter.close();
}
if (outputStream != null) {
outputStream.close();
}
}
}
// 查找行
static String findFileLine(String file, String keywork) throws IOException {
List<String> lines = readFileLines(file);
for(String line : lines) {
if (line.contains(keywork)) {
return line;
}
}
return "";
}
// 返回文件所有行
static List<String> readFileLines(String file) throws IOException {
List<String> lines = new ArrayList<>();
FileInputStream inputStream = null;
InputStreamReader streamReader = null;
BufferedReader reader = null;
try {
inputStream = new FileInputStream(file);
streamReader = new InputStreamReader(inputStream);
reader = new BufferedReader(streamReader);
String line = "";
while ((line = reader.readLine()) != null) {
lines.add(line);
}
} finally {
if (reader != null) {
reader.close();
}
if (streamReader != null) {
streamReader.close();
}
if (inputStream != null) {
inputStream.close();
}
}
return lines;
}
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询