有兩種方法,首先:
第一種方法:一次性全部讀取所有文件內容(這裏Arrays.sort(b)代表對字節進行排序,如果不需要進行刪除即可)
import java.io.FileInputStream;
import java.io.FileOutputStream;
public class Main{
public static void main(String[] args){
try {
FileInputStream fis = new FileInputStream("c:\\..\\tmp.txt");
FileOutputStream fos = new FileOutputStream("c:\\..\\tmp1.txt");
int len=0;
//一次讀取多少字節的文件,這裏可以選擇tmp.txt的所有字節長度
byte[] b = new byte[fis.available()];
while((len=fis.read(b))!=-1){
//對字節進行排序
Arrays.sort(b);
fos.write(b,0,len);
fos.flush();
}
}catch(FileNotFoundException e){
e.printStackTrace();
}catch(IOException e){
e.printStackTrace();
}
}
}
第二種方法:有時候爲了一行一行的讀取文件中的內容,因此可以用如下方法:
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Arrays;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.BufferedReader;
import java.io.BufferedWriter;;
public class Temp1 {
public static void main(String[] args) {
// TODO Auto-generated method stub
try {
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream("C:\\...\\tmp.txt"),"GB2312"));
String b="";
StringBuffer sb = new StringBuffer();
try {
while((b = br.readLine())!=null){
//得到文件內容放到sb中
sb.append(b);
//這裏可以寫自己想對每一行的處理代碼
}
String s = sb.toString();
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("C:\\...\\tmp1.txt"),"GB2312"));
bw.write(s);
bw.flush();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (UnsupportedEncodingException | FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}