首页 > 代码库 > java io流之int数组数据的插入与取出

java io流之int数组数据的插入与取出

java io流大家都很熟悉吧,有时候如果用的不熟,对于数据的处理真的很头疼,下面是对与int数组的处理。

下面是代码:

public class Stream {
    private int a[];
    private BufferedWriter bufferedWriter;
    private BufferedReader bufferedReader;
    private String pathName="e:\\stream.txt";
	
	private void random(){
		Random random=new Random(10000);
		a=new int[10000];
		for(int i=0;i<a.length;i++){
			a[i]=random.nextInt(10000);
		}
	}
    
	private void write(){
		String write=intToString(a);
		try {
			bufferedWriter=new BufferedWriter(new FileWriter(pathName));
			bufferedWriter.write(write);
			bufferedWriter.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	private void read(){
		try {
			bufferedReader=new BufferedReader(new FileReader(pathName));
			String read=bufferedReader.readLine();
			int[] array=stringToInt(read);
			for(int i=0;i<array.length;i++){
				System.out.println(array[i]);
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	private String intToString(int[] a){
		StringBuilder stringBuilder=new StringBuilder();
		for(int i=0;i<a.length;i++){
			stringBuilder.append(a[i]).append(",");
		}
		stringBuilder.deleteCharAt(stringBuilder.length()-1);
		return stringBuilder.toString();
	}
	
	private int[] stringToInt(String str){
		String[] strAry = str.split(",");
		int[] ary=new int[strAry.length];
		for(int i=0;i<strAry.length;i++){
			ary[i]=Integer.parseInt(strAry[i]);
		}
		return ary;
	}
	
	public static void main(String[] args){
        Stream stream =new Stream();
        stream.random();
        stream.write();
        stream.read();
    }
}
这里对于int数组的处理是加入一个“,”隔开,然后用String的split()处理,希望对大家有所帮助。

java io流之int数组数据的插入与取出