您的位置:首页 > 职场人生

Java面试--io

2015-08-27 13:48 501 查看
(1)

题目:给出一个整数数组,将其写入一个文件,再从文件中读出,并按整数大小逆序打印。

这道面试题是我看了好多面试题后自己编的,希望能对将要面试的人有点帮助。

对于我这个新手来说,觉得这个题目考察的基础东西还是比较多的:

1.对文件的写入和读出方面的考察

2.对不同形的数组转换方面的考察

3.对string基本用法的考察(split,substring)

4.类型转换的考察

5.对算法的考察(排序)

ps:我写的这个题目肯定有其他更好的方法,我这个就算是一个笨方法了,由于我编程功力还不深厚,而且写下面的这些代码借助了myEclipse这样先进的IDE工具,还时不时的上baidu ,google搜索一下,但在笔试的时候全屏记忆在纸上写,这样难度可想而知。看来基础真的很重要

package test;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;

/**
 * 题目:给出一个整数数组,将其写入一个文件,再从文件中读出,并按整数大小逆序打印。
 *
 */
public class Io {

    public static void main(String[] args) {
        int[] intArr = new int[]{10, -101, 2, 5, 3, 4, 6};
        try {
            System.out.println(File.separator);
            System.out.println(File.pathSeparator);
            writeFile("D:" + File.separator + "io.txt", intArr);
            int[] ints = readFileAndSort("D:" + File.separator + "io.txt");
            for (int i : ints) {
                System.out.print(i);
                System.out.print(",");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void writeFile(String str, int[] array) throws IOException {
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(str)));
        StringBuilder sb = new StringBuilder();
        for (int e : array) {
            sb.append(e).append(",");
        }
        bw.write(sb.toString());
        bw.close();
    }

    public static int[] readFileAndSort(String str) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(str)));
        String[] strings = br.readLine().toString().split(",");
        int[] ints = new int[strings.length];
        for (int i = 0; i < strings.length; i++) {
            if (strings[i] != " " && strings[i] != null)
                ints[i] = Integer.parseInt(strings[i]);

        }
        Sort(ints);
        br.close();
        return ints;
    }

    /**
     * 快速排序:找准一个基准元素,通过一趟扫描,将待排序序列分成两部分,一部分比基准元素小,一部分比基准元素大
     * @param ints
     */
    private static void Sort(int[] ints) {
        if (ints.length > 0) {
            quickSort(ints, 0, ints.length - 1);
        }
    }

    private static void quickSort(int[] array, int low, int high) {
        if (low < high) {
            int mid = getMiddle(array, low, high);
            quickSort(array, low, mid - 1);
            quickSort(array, mid + 1, high);
        }
    }

    private static int getMiddle(int[] array, int low, int high) {
        int temp = array[low];
        while (low < high) {
            while (low < high && array[high] > temp) {
                high--;
            }
            array[low] = array[high];
            while (low < high && array[low] < temp) {
                low++;
            }
            array[high] = array[low];
        }
        array[low] = temp;
        return low;
    }

}


运行结果:

在Result.txt中为:10,-101,2,5,3,4,6,

控制台打印为:-101,2,3,4,5,6,10,



(2)最近用到一些java.io包中的一些类接口,所以写了一些东西来复习。

Input和Output是同一类,而Reader和Writer另属同一类



Reader支持16位的Unicode字符的输出,而InputStream只支持8位字符输出。他们的大概结构如下:



InputStream的子类有:

FileInputStream,FilterInputStream,ObjectInputStream,StringBufferInputStream等

OutputStream的子类有:

ByteArrayOutputStream,FileOutputStream,FilterOutputStream,PipedOutputStream,ObjectOutputStream。



Reader的子类有:BufferdReader,InputStreamReader,FilterReader,StringReader,PipedReader,CharArrayReader。

Writer的子类有: BufferedWriter,CharArrayWriter,FilterWriter,OutputStreamWriter,PipedWriter,PrintWriter,StringWriter。



曾遇到一个面试题:

请选择下面的这却答案:



a. System.out 是一个PrintStream。

b. System.out 是一个OutputStream。

c. System.out 是一个FilterOutputStream。

d. System.out 不是一个PrintStream。

e. System.out 在异常时,将抛出IOExcepton。



由于System.out 是一个PrintStream的一个子类,并且PrintStream对象并没有抛出IOException异常。

所以可以看出答案:a b c

例一:InputStream读取文件的应用:

Java代码



import java.io.FileInputStream;

import java.io.FileNotFoundException;

import java.io.IOException;

import java.io.InputStream;



<span style="color: #339966;">/**

*

* @author liugao ec06 cumt

*

*/</span>

public class TestJavaIo {



<span style="color: #339966;">/**

* @param args

*/</span>

public static void main(String[] args) {

int b=0;

long num=0;

InputStream in=null;

try {

in=new FileInputStream("D:/a.txt");

} catch (FileNotFoundException e) {

System.out.println("文件找不到");

System.exit(-1);

}

try{

while((b=in.read()) !=-1){ <span style="color: #339966;">//b读取是字符的AI码</span>

System.out.println((char)b);

num++;

}

in.close();

System.out.println();

System.out.println("共读取了" + num + "个字节");



}catch(IOException e){

System.out.println("文件读取错误");

System.exit(-1);

}

}

}



例二:FileReader的应用:

Java代码



import java.io.FileNotFoundException;

import java.io.FileReader;

import java.io.IOException;



<span style="color: #339966;">/**

*

* @author ec06cumt

*

*/</span>

public class TestFileReader {



<span style="color: #339966;"> /**

* @param args

*/</span>

public static void main(String[] args) {

FileReader fr=null;

int c=0;

int ln=0;

try {

fr=new FileReader("D:/a.txt");

while((c=fr.read())!=-1){

System.out.println((char)c);

ln++;

}

fr.close();



<span style="color: #339966;">//主要这里的ln的值,当有中文字符时,一个中文字符还是算一个,

//但InputStream时就一个中文就两个,由此可以看出Reader和Input的区别</span>

System.out.println("共有:"+ln+"个字符");

} catch (FileNotFoundException e) {

e.printStackTrace();

}catch (IOException e) {

e.printStackTrace();

}

}



}





例三:BufferedReader与BufferWriter的应用:



Java代码



import java.io.BufferedReader;

import java.io.BufferedWriter;

import java.io.FileReader;

import java.io.FileWriter;

import java.io.IOException;



<span style="color: #339966;">/**

* BufferReader和BufferWriter的应用示例

* @author ec06cumt

*

*/</span>

public class TestBufferedReader {



<span style="color: #339966;">/**

* @param args

*/</span>

public static void main(String[] args) {

try {

<span style="color: #339966;">//BuffererReader等就像在原来的字节流的基础上套一个更大的水管,

//让出水量更大读取的速度更快。</span>

BufferedWriter bw=new BufferedWriter(new FileWriter("D:/aa.txt"));

BufferedReader br=new BufferedReader(new FileReader("D://aa.txt"));

String s=null;

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

s=String.valueOf(10+(long)(Math.random()*30));

bw.write(s);

bw.newLine(); <span style="color: #339966;">//创建一个换行的标记</span>



}

bw.flush(); <span style="color: #339966;"> //刷新缓冲区域。</span>

while((s=br.readLine())!=null){ <span style="color: #339966;">//readLine 就是水管的一个应用吧</span>

System.out.println(s);

}

bw.close();

br.close();

} catch (IOException e) {

System.out.println("写入错误");

}

}



}



例四:DataStream的应用:

Java代码



import java.io.ByteArrayInputStream;

import java.io.ByteArrayOutputStream;

import java.io.DataInputStream;

import java.io.DataOutputStream;

import java.io.IOException;



<span style="color: #339966;">/**

*

* @author ec06cumt

*

*/</span>

public class TestDataStream {



<span style="color: #339966;">/**

* @param args

*/</span>

public static void main(String[] args) {

ByteArrayOutputStream bos=new ByteArrayOutputStream();

DataOutputStream dos=new DataOutputStream(bos);

try {

<span style="color: #339966;">// dos.writeFloat((float) Math.random());

// dos.writeLong((long) Math.random());

// dos.writeDouble((double) Math.random());

// dos.writeChar((char) Math.random());</span>



dos.writeShort((short) Math.random());

dos.writeBoolean(true);

//注意ByteArrayInputStream的构造方法是参数要是一个数组

ByteArrayInputStream bais=new ByteArrayInputStream(bos.toByteArray());



DataInputStream dis=new DataInputStream(bais);

System.out.println(dis.available());

//System.out.println(dis.readDouble());

<span style="color: #339966;">// System.out.println(dis.readInt());

// System.out.println(dis.readFloat());

// System.out.println(dis.readDouble());

// System.out.println(dis.readChar());</span>

System.out.println(dis.readShort());



System.out.println(dis.readBoolean());

bos.close();

bais.close();



} catch (IOException e) {

e.printStackTrace();

}

}



}



例五:ObjectStream的应用

Java代码



import java.io.FileInputStream;

import java.io.FileNotFoundException;

import java.io.FileOutputStream;

import java.io.IOException;

import java.io.ObjectInputStream;

import java.io.ObjectOutputStream;

import java.io.Serializable;



<span style="color: #339966;">/**

* 对象的写入和读取

* @author ec06cumt

*

*/</span>

public class TestObjectStream {



<span style="color: #339966;">/**

* @param args

*/</span>

public static void main(String[] args) {



T t=new T();

t.k=10;



try {

FileOutputStream fos=new FileOutputStream("D:/testObjectIo.bak");

ObjectOutputStream oos=new ObjectOutputStream(fos);

oos.writeObject(t);

oos.flush();

oos.close();



FileInputStream fis=new FileInputStream("D:/testObjectIo.bak");

ObjectInputStream bis=new ObjectInputStream(fis);

T tReader= (T) bis.readObject();

System.out.println(tReader.i + " " +tReader.j + " "+tReader.d + " " + tReader.k);



} catch (FileNotFoundException e) {

e.printStackTrace();

}catch(IOException e1){

e1.printStackTrace();

}catch(ClassNotFoundException e2){

e2.printStackTrace();

}

}



}



class T implements Serializable{

int i=2;

int j=4;

double d=2.5;

transient int k=15;

// int k=15;

}







例六:文件的目录复制





Java代码



import java.io.File;

import java.io.FileInputStream;

import java.io.FileNotFoundException;

import java.io.FileOutputStream;

import java.io.IOException;

import java.io.InputStream;

import java.io.OutputStream;





public class JavaIoCopyFile {



<span style="color: #339966;">/**

* Author:liugao ec06-2 cumt

* @param args

*/</span>

public static void main(String[] args) {



File sourceFile=new File("D:/test");

File targetFile=new File("F:/jstl");

copy(sourceFile,targetFile);



}



private static void copy(File sourceFile, File targetFile) {

File tarpath=new File(targetFile,sourceFile.getName());

if(sourceFile.isDirectory()){

tarpath.mkdir();

File[] dir=sourceFile.listFiles();

for(int i=0;i<dir.length;i++){

copy(dir[i],tarpath);

}

}else{

try {

InputStream is=new FileInputStream(sourceFile);

OutputStream os=new FileOutputStream(tarpath);



byte[] buf=new byte[1024];

int len=0;

while((len= is.read(buf))!=-1){

os.write(buf);

}

System.out.println("复制完成");

is.close();

os.close();



} catch (FileNotFoundException e) {

e.printStackTrace();

}catch(IOException e1){

e1.printStackTrace();

}

}

}







}







常用的也就是这些方法吧。。。。



内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: