package test;
import java.io.*;
import java.util.*;
public class FileReadWrite {
/**
* 描述:readFile
*
* @param dir
* @return
* @throws IOException
* @CreateOn Jul 28, 2008 2:16:23 PM
* @author chun_chang
*/
public StringBuffer readFile(String dir) throws IOException {
StringBuffer buffer = null;
try {
buffer = new StringBuffer();
InputStream fis = new FileInputStream(dir);
BufferedReader reader = new BufferedReader(new InputStreamReader(fis));
String line = null;// 用来保存每行读取的内容
line = reader.readLine(); // 读取第一行
while (line != null) { // 如果 line 为空说明读完了
buffer.append(line); // 将读到的内容添加到 buffer 中
buffer.append("/n"); // 添加换行符
line = reader.readLine(); // 读取下一行
}
System.out.println(buffer); // 将读到 buffer 中的内容写出来
fis.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return buffer;
}
/**
* 描述:writeFile
*
* @param dir
* @param content
* @param flag
* true:追加,false:覆盖
* @throws IOException
* @CreateOn Jul 28, 2008 3:58:07 PM
* @author chun_chang
*/
public void writeFile(String dir, String content, boolean flag) throws IOException {
try {
// 文件的追加或修改
OutputStream fos = new FileOutputStream(dir, flag);
OutputStreamWriter osw = new OutputStreamWriter(fos);
osw.write(content, 0, content.length());
osw.flush();
fos.close();
} catch (FileNotFoundException e) {
// 文件不存在的时候
File write = new File(dir);
BufferedWriter bw = new BufferedWriter(new FileWriter(write, flag));
bw.write(content + "/r/n"); // 只适用Windows系统
bw.close();
}
}
/**
* 描述:sort 冒泡排序(降序)
* @param src
* @CreateOn Jul 29, 2008 9:49:15 AM
* @author chun_chang
*/
public void sort(int[] src) {
int i, m = 0;
for (i = 0; i < src.length - 1; i++) {
for (m = i + 1; m < src.length; m++) {
if (src[i] < src[m]) {
int temp = src[i];
src[i] = src[m];
src[m] = temp;
}
}
}
}
/**
* 描述:strToInt String[]转化为int[]数组
* @param arrs
* @return
* @CreateOn Jul 29, 2008 9:47:37 AM
* @author chun_chang
*/
public int[] strToInt(String[] arrs) {
int[] arri = new int[arrs.length];
for (int i = 0; i < arrs.length; i++) {
arri[i] = Integer.parseInt(arrs[i]);
}
return arri;
}
/**
* 描述:intToStr int[]转化为String[]数组
* @param arri
* @return
* @CreateOn Jul 29, 2008 9:47:34 AM
* @author chun_chang
*/
public String[] intToStr(int[] arri) {
String[] arrs = new String[arri.length];
for (int i = 0; i < arri.length; i++) {
arrs[i] = String.valueOf(arrs[i]);
}
return arrs;
}
/**
* 描述:main
*
* @param args
* @CreateOn Jul 28, 2008 1:58:24 PM
* @author chun_chang
*/
public static void main(String[] args) {
FileReadWrite frw = new FileReadWrite();
String result = null;
String dirr = "C://in.txt";
String dirw = "C://out.txt";
try {
result = frw.readFile(dirr).toString();
// frw.writeFile(dirw, content);//直接写入content
String str = result.replaceAll("/n", " ");//回车符替换为空格
String array[] = str.split(" ");//按空格 划分为数组
int[] arri = frw.strToInt(array);
frw.sort(arri);//冒泡排序(降序)
//Arrays.sort(arri)//util包自带排序(升序)
frw.writeFile(dirw, Arrays.toString(arri), false);
} catch (IOException e) {
e.printStackTrace();
}
}
}