java 怎么将数据写入TXT文件

怎么将int数组数据写入TXT文件 例如将int A[20];中的20个数据写入result.txt文件中

求大虾告诉我关键几句代码

定义一个输出文件,然后输出就可以了,具体见下面的代码

 import java.io.*;

 public class StreamDemo

 {

  public static void main(String args[])

  {

   File f = new File("c:\\temp.txt") ;

   OutputStream out = null ;

   try 

   {

    out = new FileOutputStream(f) ;

   } 

   catch (FileNotFoundException e) 

   {

    e.printStackTrace();

   }

   // 将字符串转成字节数组

   byte b[] = "Hello World!!!".getBytes() ;

   try 

   {

    // 将byte数组写入到文件之中

    out.write(b) ;

   } 

   catch (IOException e1) 

   {

    e1.printStackTrace();

   }

   try 

   {

    out.close() ;

   } 

   catch (IOException e2) 

   {

    e2.printStackTrace();

   }

  

   // 以下为读文件操作

   InputStream in = null ;

   try 

   {

    in = new FileInputStream(f) ;

   } 

   catch (FileNotFoundException e3) 

   {

    e3.printStackTrace();

   }

   // 开辟一个空间用于接收文件读进来的数据

   byte b1[] = new byte[1024] ;

   int i = 0 ;

   try 

   {

   // 将b1的引用传递到read()方法之中,同时此方法返回读入数据的个数

    i = in.read(b1) ;

   } 

   catch (IOException e4) 

   {

    e4.printStackTrace();

   }

   try 

   {

    in.close() ;

   } 

   catch (IOException e5) 

   {

    e5.printStackTrace();

   }

   //将byte数组转换为字符串输出

   System.out.println(new String(b1,0,i)) ;

  }

 }

温馨提示:答案为网友推荐,仅供参考
第1个回答  推荐于2017-10-11
import java.io.FileWriter;
import java.io.IOException;

public class Test02 {

void writefile() throws IOException {
FileWriter fileWriter=new FileWriter("c:\\Result.txt");
int [] a=new int[]{111,222,333,444,555,666};
for (int i = 0; i < a.length; i++) {
fileWriter.write(String.valueOf(a[i])+" ");

}
fileWriter.flush();
fileWriter.close();
}
public static void main(String[] args) throws IOException {
new Test02().writefile();
}
}
//你看看,就这两句,测试通过了!本回答被提问者采纳
第2个回答  2008-12-14
I/O流
PrintWriter实现
第3个回答  2008-12-13
用FileWriter
file f = new file(filename);
FileWriter fw=new FileWriter(f);
fw.write(new String(A,0,20));
第4个回答  2008-12-14
回答的真好。
不用补充了。
相似回答