现有一文件test1.txt,格式为:
1000
1 \120 abcdefg
2 \30 hijklmn
3 \420 opqrstu要转化为以下的文件test2.txt
1000
1 \-880 abcdefg
2 \-970 hijklmn
3 \-580 opqrstu即减去前面的数字1000(当然不一定是1000,可能是变化的,就是减去第一行那数字),不知道怎么实现?
1000
1 \120 abcdefg
2 \30 hijklmn
3 \420 opqrstu要转化为以下的文件test2.txt
1000
1 \-880 abcdefg
2 \-970 hijklmn
3 \-580 opqrstu即减去前面的数字1000(当然不一定是1000,可能是变化的,就是减去第一行那数字),不知道怎么实现?
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new FileReader("e:\\text1.txt"));
int BasedNum = Integer.parseInt(br.readLine()); //得到1000
String str1 = br.readLine(); //得到第二行数据
String str2 = br.readLine(); //得到第三行数据
String str3 = br.readLine(); //得到第四行数据 String str1Int = str1.substring(4, str1.lastIndexOf(" ") - 1).trim();
String str2Int = str2.substring(4, str2.lastIndexOf(" ") - 1).trim();
String str3Int = str3.substring(4, str3.lastIndexOf(" ") - 1).trim(); String str1NewInt = String
.valueOf(Integer.parseInt(str1Int) - BasedNum);
String str2NewInt = String
.valueOf(Integer.parseInt(str2Int) - BasedNum);
String str3NewInt = String
.valueOf(Integer.parseInt(str3Int) - BasedNum); String str1New = str1.replaceAll(str1Int, str1NewInt); //得到第一行新的数据
String str2New = str2.replaceAll(str2Int, str2NewInt); //得到第二行新的数据
String str3New = str3.replaceAll(str3Int, str3NewInt); //得到第三行新的数据 PrintWriter pw = new PrintWriter(new BufferedWriter(new FileWriter(
"e:\\text2.txt")));
pw.println(str1New);
pw.println(str2New);
pw.println(str3New);
pw.close(); }
}
import java.io.*;
public class Test{
public static void main(String args[]){
try{
File inputfile=new File("test1.txt");
File outputfile=new File("test2.txt");
PrintWriter output=new PrintWriter(new FileWriter(outputfile));
Scanner input= new Scanner(inputfile);int minuend=input.nextInt();
output.println(minuend);String token;
while((token=input.next())!=null){
output.print("fsadfsd"+" ");/*
token=input.next().substring(1);
int temp=Integer.parseInt(token);
output.print("\\"+(temp-minuend)+" ");
output.println(input.next());*/
}
input.close();
output.close();
}
catch(Exception ex){
System.err.print(ex.getMessage());
}
}
}
=====================
test result
test1.txt:
1000
1 \120 abcdefg
2 \30 hijklmn
3 \420 opqrstutest2.txt:
1000
1 \-880 abcdefg
2 \-970 hijklmn
3 \-580 opqrstu