2015-05-11 17 views
6

Nhiệm vụ:ký tự lạ khi sử dụng byte dựa trên FileOutputStream, char dựa trên FileWriter là OK

Viết một ứng dụng Java tạo ra một tập tin trên hệ thống tập tin địa phương của bạn chứa 10000 giá trị số nguyên được tạo ngẫu nhiên giữa 0 và 100000. Hãy thử điều này trước tiên bằng cách sử dụng luồng dựa trên byte và sau đó thay vào đó bằng cách sử dụng luồng dựa trên char. So sánh kích thước tệp được tạo bởi hai phương pháp khác nhau .

Tôi đã tạo luồng dựa trên byte. Sau khi tôi chạy chương trình này, trong fileOutput tôi nhận được một số ký hiệu lạ. Tôi có làm điều gì sai ?

import java.io.File; 
import java.io.FileOutputStream; 
import java.io.IOException; 
import java.util.Random; 

public class Bytebased { 

    public static void main(String[] args) throws IOException { 

    File outFile = new File("fileOutput.txt"); 
    FileOutputStream fos = new FileOutputStream(outFile); 

    Random rand = new Random(); 
    int x; 

    for(int i=1;i<=10001;i++){ 
     x = rand.nextInt(10001); 
     fos.write(x); 
    } 
    fos.close(); 
    } 
} 

Khi tôi đang sử dụng dòng char dựa trên hoạt động:

import java.io.File; 
import java.io.FileWriter; 
import java.io.IOException; 
import java.util.Random; 

public class Charbased { 

    public static void main(String[] args) throws IOException { 

    File outFile = new File("fileOutput2.txt"); 
    FileWriter fw = new FileWriter(outFile); 

    Random rand = new Random(); 
    int x; 
    String y; 
    for(int i=1;i<=10001;i++){ 
     x = rand.nextInt(10001); 
     y=x + " "; 
     fw.write(y); 
    } 

    fw.close(); 

    } 
} 

Trả lời

2

Viết một đầu ra thường xuyên vào một tập tin trực tiếp từ một FileOutputSream sẽ làm điều đó, bạn cần phải chuyển đổi sản lượng của bạn vào byte đầu tiên . Một cái gì đó như:

public static void main(String[] args) throws IOException { 

    File outFile = new File("fileOutput.txt"); 
    FileOutputStream fos = new FileOutputStream(outFile); 

    String numbers = ""; 

    Random rand = new Random(); 

    for(int i=1;i<=10001;i++){ 
     numbers += rand.nextInt(10001); 
    } 

    byte[] bytesArray = numbers.getBytes(); 
    fos.write(bytesArray); 
    fos.flush(); 
    fos.close(); 
} 
Các vấn đề liên quan