
Java,在main方法中,随机生成0-100的整数50个,将这50个数以二进制形式写到文件中。
编写程序,在main方法中,随机生成0-100的整数50个,将这50个数以二进制形式写到文件中。(其中生成随机数的方法为Math.random()*100);编写另一个程...
编写程序,在main方法中,随机生成0-100的整数50个,将这50个数以二进制形式写到文件中。(其中生成随机数的方法为Math.random() * 100);编写另一个程序,在main方法中,将前面所生成的50个数从文件中读取出来并打印。
我开始的想法是这样的。 展开
我开始的想法是这样的。 展开
1个回答
2018-01-02 · 百度知道合伙人官方认证企业

北京尚学堂科技有限公司是一家从事JAVA、大数据、web前端、网络在线教育、互联网架构师、Android、ios技术开发、咨询为一体的软件公司。公司由海外留学人员和国内IT人士创建。
向TA提问
关注

展开全部
将数字写在文件中:
public class Example implements Serializable {
public static void main(String[] args) {
// 放随机产生数字的数组
int[] arrayInt = new int[50];
// 放随机产生50个数字并且放在数组中
for (int i = 0; i < 50; i++) {
Random random = new Random();
int ii = random.nextInt(100);
arrayInt[i] = ii;
}
try {
// 将这50个数以二进制形式写到文件中
FileOutputStream fos = new FileOutputStream("e:/number.txt");
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(arrayInt);
oos.close();
fos.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
从文件中读取数字并且打印:
public class Test implements Serializable {
public static void main(String[] args) {
try {
// 将前面所生成的50个数从文件中读取出来
FileInputStream fis = new FileInputStream("e:/number.txt");
ObjectInputStream ois = new ObjectInputStream(fis);
int[] intArray = (int[]) ois.readObject();
// 遍历数组,打印数字
for (int i = 0; i < intArray.length; i++) {
System.out.print(intArray[i] + " ");
}
ois.close();
fis.close();
}
catch (Exception e) {
e.printStackTrace();
}
}
}
运行效果:
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询