我有一个类似下面的srt文件,我想删除空行:第3行
**
1
Line1: 00:00:55,888 --> 00:00:57,875.
Line2:Antarctica
Line3:
Line4:2
Line5:00:00:58,375 --> 00:01:01,512
Line6:An inhospitable wasteland.
**
FileInputStream fin = new FileInputStream("line.srt");
FileOutputStream fout = new FileOutputStream("m/line.srt");
int i = 0;
while(((i =fin.read()) != -1)){
if(i != 0)
fout.write((byte)i);
}
答案 0 :(得分:1)
你去吧。步骤进行:
1)FileInputStream fin = new FileInputStream("line.srt");
这是在下一步将文件送到bufferedreader
2)BufferedReader reader = new BufferedReader(new InputStreamReader(fin));
将文本文件提供给buffereader
3)PrintWriter out = new PrintWriter("newline.srt");
使用打印编写器写入新文本文件中每行的字符串
4)String line = reader.readLine();
阅读下一行
5)while(line != null){
if (!line.trim().equals("")) {
检查该行是否为空且该行不为空
6)out.println(line);
将输出行(非空)写入输出.srt文件
7)line = reader.readLine();
获得新行
8)out.close();
最后关闭PrintWriter ......
import java.io.*;
class RemoveBlankLine {
public static void main(String[] args) throws FileNotFoundException, IOException{
FileInputStream fin = new FileInputStream("line.srt");
BufferedReader reader = new BufferedReader(new InputStreamReader(fin));
PrintWriter out = new PrintWriter("newline.srt");
int i = 0;
String line = reader.readLine();
while(line != null){
if (!line.trim().equals("")) {
out.println(line);
}
line = reader.readLine();
}
out.close();
}
}
INPUT:
**
1
00:00:55,888 --> 00:00:57,875.
Antarctica
2
00:00:58,375 --> 00:01:01,512
An inhospitable wasteland.
**
输出:
**
1
00:00:55,888 --> 00:00:57,875.
Antarctica
2
00:00:58,375 --> 00:01:01,512
An inhospitable wasteland.
**
顺便说一句,确保在提出问题时你很清楚,因为你陈述问题的方式我假设Line1,Line2等是输入文件的一部分,我准备了另一个我必须改变的解决方案...确保你清晰准确,以便得到正确的答案!
答案 1 :(得分:1)
您可以尝试以下内容:
BufferedReader br = null;
BufferedWriter bw = null;
try {
br = new BufferedReader(new FileReader("line.srt"));
bw = new BufferedWriter(new FileWriter("m/line.srt"));
for(String line; (line = br.readLine()) != null; ) {
if(line.trim().length() == 0) {
continue;
} else {
bw.write(line);
bw.newLine();
}
}
bw.flush();
bw.close();
br.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
答案 2 :(得分:1)
希望这个帮助
public static void main(String[] args) throws FileNotFoundException, IOException {
Path myPath = Paths.get("e:\\", "1.txt");
List<String> ls ;
ls = Files.readAllLines(myPath, StandardCharsets.US_ASCII);
PrintWriter out = new PrintWriter("e:\\2.txt");
for (int i = 0; i < ls.size(); i++) {
String []temp = ls.get(i).split(":");
if(temp.length>1) {
out.println(ls.get(i));
}
}
out.close();
}