首页 > 代码库 > Java—从文件中读取数据

Java—从文件中读取数据

1、FileInputStream()

              // 构建字节输入流对象,参数为文件名              FileInputStream fin = new FileInputStream("message");              System.out.println("输入流可读入字节数:" + fin.available());              // 建立byte型数组b,从输入流读取的数据暂时存放在b中              byte b[] = new byte[fin.available()];              // 从输入流读取数据              fin.read(b);              String str5=new String(b);              System.out.println(str5);              // 关闭输入流,对文件的操作,一定要在最后关闭输入输出流              fin.close();

2、RandomAccessFile()

              String str6="";              ArrayList<String> strs=new ArrayList<String>();              RandomAccessFile file=new RandomAccessFile("message","r");              str6 = file.readLine();              while(str6!=null){                  strs.add(str6);                  str6 = file.readLine();              }              for(int j=0;j<strs.size();j++){                  System.out.println(strs.get(j));              }              file.close();

3、File

              File file2=new File("message");              if(file2.exists()&&file2.isFile()){                  InputStream is=new FileInputStream(file2);                  byte[] buf = new byte[is.available()];                  System.out.println(is.available());                   while(is.read(buf)!=-1){                  //每次读取打印                      System.out.println(new String(buf));                  }              }

4、避免乱码

            File file3 = new File("message");            if (file3.exists() && file3.isFile()) {                try {                    InputStream is = new FileInputStream(file3);                    InputStreamReader reader = new InputStreamReader(is,"utf-8");//                    char[] cbuf = new char[is.available()];//字符,字节                                        StringBuffer sb2=new StringBuffer();//2                    while (reader.read(cbuf) != -1) {                        sb2.append(cbuf);                    }                    System.out.println(sb2.toString());                                    } catch (Exception e) {                }            }

5、BufferedReader

            File file = new File("message");            try {                InputStream is = new FileInputStream(file);                if (file.exists() && file.isFile()) {                    BufferedReader br = new BufferedReader(                            new InputStreamReader(is, "utf-8"));                    StringBuffer sb2 = new StringBuffer();                    String line = null;                    while ((line = br.readLine()) != null) {                        sb2.append(line + "\n");                    }                    br.close();                    System.out.println(sb2.toString());                }            } catch (Exception e) {            }

 

Java—从文件中读取数据