日期:2014-05-20 浏览次数:20731 次
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; public class Test { public static void main(String[] args) { File src = new File("f:/1.txt"); File dist = new File("f:/1_.txt"); transpose(src, dist, " "); } /** * 原文件内容: * 1.1 1.2 1.3 1.4 1.5 * 2.1 2.2 2.3 2.4 2.5 * 3.1 3.2 3.3 3.4 3.5 * 4.1 4.2 4.3 4.4 4.5 * 5.1 5.2 5.3 5.4 5.5 * 6.1 6.2 6.3 6.4 6.5 * 转置后: * 1.1 2.1 3.1 4.1 5.1 6.1 * 1.2 2.2 3.2 4.2 5.2 6.2 * 1.3 2.3 3.3 4.3 5.3 6.3 * 1.4 2.4 3.4 4.4 5.4 6.4 * 1.5 2.5 3.5 4.5 5.5 6.5 * @param src 源文件 * @param dist 新文件 * @param separator 列分隔符 * @since 2008-1-21 */ private static void transpose(File src, File dist, String separator) { BufferedReader br = null; BufferedWriter bw = null; int row = 0; try { // 检查矩阵的行数 br = new BufferedReader(new FileReader(src)); String str; while((str = br.readLine()) != null) { row++; } br.close(); // 读成取矩阵文件 br = new BufferedReader(new FileReader(src)); String[][] matrix = new String[row][]; row = 0; while((str = br.readLine()) != null) { matrix[row++] = str.split(separator); } br.close(); // 重新写入文件 bw = new BufferedWriter(new FileWriter(dist)); for(int j = 0; j < matrix[0].length; j++) { for(int i = 0; i < matrix.length; i++) { if(i > 0) { // 写入分隔符 bw.write(separator); } bw.write(matrix[i][j]); } bw.newLine(); } bw.close(); }catch(IOException e) { e.printStackTrace(); } } }