码迷,mamicode.com
首页 > 编程语言 > 详细

java读写文件及保留指定位小数

时间:2016-01-19 12:46:55      阅读:255      评论:0      收藏:0      [点我收藏+]

标签:

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("\t");
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])+"\t");
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])+"\t");
10 
11             }
12             if(i!=transformB.length-1)
13                 w2.newLine();//插入换行符
14 
15         }
16         w2.close();

参考:

https://segmentfault.com/q/1010000000359840

http://my.oschina.net/xiangtao/blog/17078

http://glblong.blog.51cto.com/3058613/1312340

java读写文件及保留指定位小数

标签:

原文地址:http://www.cnblogs.com/lz3018/p/5141706.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!