1)先上代码:
1 public static void main(String[] args)throws IOException{ 2 3 4 double[][] B=new double[1043][21025]; 5 double[][] transformB=new double[21025][1043]; 6 7 8 String filename="/home/hadoop/srcData/B.txt"; 9 final LineIterator it = FileUtils.lineIterator(new File(filename), "UTF-8"); 10 try { 11 int i=-1; 12 //DecimalFormat df=new DecimalFormat("#.0000"); 13 while (it.hasNext()) { 14 ++i; 15 final String line = it.nextLine(); 16 String[] ele=line.split(" "); 17 for(int j=0;j<ele.length;++j){ 18 B[i][j]=Double.valueOf(ele[j]).doubleValue();//String -->double 19 //B[i][j]=Double.valueOf(df.format(B[i][j]) ).doubleValue(); 20 } 21 } 22 } finally { 23 it.close(); 24 } 25 //B 26 for (int i=0;i<B[0].length;++i) 27 for (int j=0;j<B.length;++j){ 28 transformB[i][j]=B[j][i]; 29 } 30 31 String fileName2="/home/hadoop/srcData/transB.txt"; 32 BufferedWriter w2=new BufferedWriter(new FileWriter(fileName2)); 33 for (int i=0;i<transformB.length;++i){ 34 for (int j=0;j<transformB[i].length;++j) 35 { 36 w2.write(String.valueOf(transformB[i][j])+" "); 37 38 } 39 if(i!=transformB.length-1) 40 w2.newLine(); 41 42 } 43 w2.close();
2)读文件,其中直接从文件中读取文件的简洁形式如下,每次读取一行,需要使用commons-io的FileUtils。
1 import org.apache.commons.io.FileUtils; 2 import org.apache.commons.io.LineIterator; 3 4 final LineIterator it = FileUtils.lineIterator(new File(""), "UTF-8"); 5 try { 6 while (it.hasNext()) { 7 final String line = it.nextLine(); 8 } 9 } finally { 10 it.close(); 11 }
3)写文件:
1 import java.io.IOException; 2 import java.io.FileWriter; 3 import java.io.BufferedWriter; 4 String fileName2="/home/hadoop/srcData/transB.txt"; 5 BufferedWriter w2=new BufferedWriter(new FileWriter(fileName2)); 6 for (int i=0;i<transformB.length;++i){ 7 for (int j=0;j<transformB[i].length;++j) 8 { 9 w2.write(String.valueOf(transformB[i][j])+" "); 10 11 } 12 if(i!=transformB.length-1) 13 w2.newLine();//插入换行符 14 15 } 16 w2.close();
参考:
https://segmentfault.com/q/1010000000359840