Java 编写一个程序,判断"d:/a.txt"文件是否存在 ,如果不存在则首先新建一个文件。然

,向 其中添加新数据,使用字节流将随机生成的50 个整数写入文件中,每个数用“-”隔开。
然后再把它们读出来。

package com.zy.daozhi;


import java.io.File;

import java.io.FileWriter;

import java.io.IOException;

import java.util.Random;


public class Demo2 {

public static void main(String[] args) {

try {

File f=new File("D:/yi.txt");

FileWriter fw =new FileWriter(f);;

Random rom = new Random();

if(f.exists()){

System.out.println("文件已存在。。。");

}else{

f.createNewFile();

}

Random random = new Random();

        for(int i = 0; i < 50;i++) {

        System.out.println(Math.abs(random.nextInt())%50);

         

        fw.write(Math.abs(random.nextInt())%50+"-");

        }

        fw.flush();

        fw.close();

} catch (IOException e) {

e.printStackTrace();

}

}

}


温馨提示:答案为网友推荐,仅供参考
第1个回答  2014-11-21
public class Test01 {

public static void main(String[] args) {

try {
File file=new File("D:/wr.txt");
FileWriter fw = new FileWriter(file);
Random rom = new Random();
String str ="-"; //分隔符
if (file.exists()) {
//文件存在,就写数据进去。
for(int i =0; i<50; i++){
int n = rom.nextInt();
System.out.println(n);
fw.write(n+str);
}
}else{
//文件不存在就创建
file.createNewFile();
}
fw.flush();
fw.close();

} catch (IOException e) {

e.printStackTrace();
}
}
}
你可以试试!本回答被网友采纳