java語言程式設計基礎篇--第十九章--練習題19.1

來源:互聯網
上載者:User
package cn.edu.hnnu.lanqiao.nineteen;


import java.io.File;
import java.io.PrintWriter;
/*
 * 
 * 建立一個文本,寫入資料 100個隨機整數 空格分隔
 * 檔案若存在,則追加資料。
 * 2013年8月1日 17:08:34
 */
import java.io.IOException;
import java.util.Random;
import java.util.Scanner;


public class Exercise19_1 {


/**
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
// 檔案對象建立
File f = new File("Exercise19_1");
if(f.exists()==false){
f.createNewFile();
}

// 這裡設計很差。如果原來的資料很多,每次都要拷貝。應該使用FlieWrite重寫
// 儲存已經存在的資料
Scanner input = new Scanner(f); //簡單的文本掃描器
StringBuffer sb = new StringBuffer("");
while (input.hasNext())
sb.append(input.next());
input.close(); //用完就關閉


PrintWriter pw = new PrintWriter(f); // 檔案被截取為o
pw.append(sb);
//追加100個隨機整數
Random rd = new Random();
for (int i = 0; i < 100; i++)
pw.append(rd.nextInt() + " ");

//重新整理和關閉流
pw.flush();
pw.close();




}
}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.