在做数据集的时候,由于有一万多条数据,作为程序猿的我,就想偷懒了。
首先我们来介绍一下,两个.txt文件拼装在一起,每行各取一个,代码如下:
public static void showFileContent3(String fileName1,String fileName2) throws IOException {
File file1 = new File(fileName1);
File file2 = new File(fileName2);
try {
FileInputStream fis = new FileInputStream(file1);
InputStreamReader isr = new InputStreamReader(fis);
BufferedReader br = new BufferedReader(isr);
StringBuffer buf = new StringBuffer();
FileInputStream fis2 = new FileInputStream(file2);
InputStreamReader isr2 = new InputStreamReader(fis2);
BufferedReader br2 = new BufferedReader(isr2);
StringBuffer buf2 = new StringBuffer();
int line = 1;
String temp = "";
String temp2 = "";
// 一次读入一行,直到读入null为文件结束
while ((temp = br.readLine()) != null && (temp2 = br2.readLine())!=null) {
// 显示行号
// 追加内容
buf.append("# "+temp.substring(6,temp.length())+'\n');
line=0;
buf.append(temp2.substring(6,temp2.length())+'\n');
System.out.println(line + ": " + temp);
line++;
}
br.close();
FileOutputStream fos = new FileOutputStream(file1);
PrintWriter pw = new PrintWriter(fos);
pw.write(buf.toString().toCharArray());
pw.flush();
pw.close();
} catch (IOException e) {
e.printStackTrace();
} finally {
}
}
public static void main(String[] args) throws IOException {
String fileName = "D:/a1.txt";
//进行拼接
String fileName1="D:/a1.txt";
String fileName2="D:/a2.txt";
//WriteStreamAppend.showFileContent3(fileName1,fileName2);
}
对每行对数据进行操作,比如在偶数行的某位加上数字或字符等信息:代码如下
public static void showFileContent(String fileName) throws IOException {
File file = new File(fileName);
try {
FileInputStream fis = new FileInputStream(file);
InputStreamReader isr = new InputStreamReader(fis);
BufferedReader br = new BufferedReader(isr);
StringBuffer buf = new StringBuffer();
int line = 1;
String temp = "";
// 一次读入一行,直到读入null为文件结束
while ((temp = br.readLine()) != null) {
// 显示行号
if(line==2){
// 追加内容
buf.append(temp+" -1.0 -1.0 -1.0 -1.0 -1.0 -1.0 -1.0 -1.0 -1.0 -1.0 -1.0 -1.0 -1.0 -1.0 -1.0 0.8"+'\n');
line=0;
}else {
buf.append(temp+'\n');
}
System.out.println(line + ": " + temp);
line++;
}
br.close();
FileOutputStream fos = new FileOutputStream(file);
PrintWriter pw = new PrintWriter(fos);
pw.write(buf.toString().toCharArray());
pw.flush();
pw.close();
} catch (IOException e) {
e.printStackTrace();
} finally {
}
}
public static void main(String[] args) throws IOException {
String fileName = "D:/a1.txt";
//加置信度
WriteStreamAppend.showFileContent(fileName); // 显示文件内容
}