理解IO:http://www.importnew.com/23708.html

一、读写文件:

FileInputStream

该流用于从文件读取数据,它的对象可以用关键字 new 来创建。

有多种构造方法可用来创建对象。

可以使用字符串类型的文件名来创建一个输入流对象来读取文件:

InputStream f = new FileInputStream("C:/java/hello");

也可以使用一个文件对象来创建一个输入流对象来读取文件。我们首先得使用 File() 方法来创建一个文件对象:

File f = new File("C:/java/hello");
InputStream out = new FileInputStream(f);

FileOutputStream

该类用来创建一个文件并向文件中写数据。

如果该流在打开文件进行输出前,目标文件不存在,那么该流会创建该文件。

有两个构造方法可以用来创建 FileOutputStream 对象。

使用字符串类型的文件名来创建一个输出流对象:

OutputStream f = new FileOutputStream("C:/java/hello")

也可以使用一个文件对象来创建一个输出流来写文件。我们首先得使用File()方法来创建一个文件对象:

File f = new File("C:/java/hello");
OutputStream f = new FileOutputStream(f);
import java.io.*;
 
public class fileStreamTest2{
  public static void main(String[] args) throws IOException {
    
    File f = new File("a.txt");
    // 构建FileOutputStream对象,文件不存在会自动新建
    FileOutputStream fop = new FileOutputStream(f);
    // 构建OutputStreamWriter对象,参数可以指定编码,默认为操作系统默认编码,windows上是gbk
    OutputStreamWriter writer = new OutputStreamWriter(fop, "UTF-8");
    // 写入到缓冲区
    writer.append("中文输入");
    //换行
    writer.append("\r\n");
    // 刷新缓存冲,写入到文件,如果下面已经没有写入的内容了,直接close也会写入
    writer.append("English");
    //关闭写入流,同时会把缓冲区内容写入文件,所以上面的注释掉
    writer.close();
    // 关闭输出流,释放系统资源
    fop.close();
 


    // 构建FileInputStream对象
    FileInputStream fip = new FileInputStream(f);
    // 构建InputStreamReader对象,编码与写入相同
    InputStreamReader reader = new InputStreamReader(fip, "UTF-8");
      // 转成char加到StringBuffer对象中
    StringBuffer sb = new StringBuffer();
    while (reader.ready()) {
      sb.append((char) reader.read());
    }
    System.out.println(sb.toString());
    // 关闭读取流
    reader.close();
    // 关闭输入流,释放系统资源
    fip.close();
 
  }
}

 写文件:

String tPath = request.getSession().getServletContext().getRealPath("/");
        FileOutputStream outputStream = null;
        try {
            if (fileType.equals("doc") || fileType.equals("docx")) {
                String folderPath = tPath.substring(0,tPath.lastIndexOf("\\")) + "/uploadfiles/conferencefile/"+topicInfo.getId();
                tPath = folderPath +"/"+ fileName + "." + fileType;
                //--------写入文件内容-----------------
                File folder = new File(folderPath);
                if(!folder.exists())    
                {   
                    folder.mkdirs();    
                }    
                File file = new File(tPath);
                if(!file.exists())    
                {   
                    try {    
                        file.createNewFile();    
                    } catch (IOException e) {  
                        e.printStackTrace();    
                    }    
                }    
                outputStream = new FileOutputStream(file);
                byte[] bytes = Base64.decodeBase64(base64String);
                outputStream.write(bytes,0,bytes.length);
                //-----------------------------------
            }
        } catch (Exception e) {
        }
        finally {
            try {
                outputStream.close();
            } catch (IOException e) {
                // TODO 自动生成的 catch 块
                e.printStackTrace();
            }
        }

 

二、创建目录:

判断文件是否存在

File file = new File(filePath + builder.toString());
        if(!file.exists())    
        {    
            try {    
                file.createNewFile();    
            } catch (IOException e) {  
                e.printStackTrace();    
            }    
        }    

判断文件夹是否存在

File类中有两个方法可以用来创建文件夹:

  • mkdir( )方法创建一个文件夹,成功则返回true,失败则返回false。失败表明File对象指定的路径已经存在,或者由于整个路径还不存在,该文件夹不能被创建。
  • mkdirs()方法创建一个文件夹和它的所有父文件夹。
File filePath = new File("D:\\Video");
if (!filePath.exists()) {
     filePath.mkdirs();
}

三、读取目录:

判断是文件夹还是文件

import java.io.File;
 
public class DirList {
  public static void main(String args[]) {
    String dirname = "/tmp";
    File f1 = new File(dirname);
    if (f1.isDirectory()) {
      System.out.println( "目录 " + dirname);
      String s[] = f1.list();
      for (int i=0; i < s.length; i++) {
        File f = new File(dirname + "/" + s[i]);
        if (f.isDirectory()) {
          System.out.println(s[i] + " 是一个目录");
        } else {
          System.out.println(s[i] + " 是一个文件");
        }
      }
    } else {
      System.out.println(dirname + " 不是一个目录");
    }
  }
}

四、删除目录或文件

删除文件可以使用 java.io.File.delete() 方法。

删除文件及目录

//删除文件及目录
  public static void deleteFolder(File folder) {
    File[] files = folder.listFiles();
        if(files!=null) { 
            for(File f: files) {
                if(f.isDirectory()) {
                    deleteFolder(f);
                } else {
                    f.delete();
                }
            }
        }
        folder.delete();
    }

五、读写excel文件

需要jxl.jar jar包支持,jxl.jar好像不支持.xlsx格式excel文件,需要把.xlsx格式的excel文件另存为.xls格式文件

使用poi读取excel文件,HSSFWorkbook与XSSFWorkbook,前一个可以用来解析以.xls结尾的excel,后一个可以用来解析.xlsx结尾的excel

poi:

java-文件和I/O
//读取excel文件内容
            List<User> userExcel = new ArrayList<>();
            File file = null;
            try {
                file = new File(filePath);
            } catch (Exception e) {
                responseResult.setMsg("检查文件路径是否正确:"+filePath);
                return responseResult;
            }
            FileInputStream fStream = new FileInputStream(file);
            XSSFWorkbook xss = new XSSFWorkbook(fStream);
            XSSFSheet sheet = xss.getSheetAt(0);
            for(int i=0;i<sheet.getLastRowNum();i++) {
                Row row = sheet.getRow(i);
                User user = new User();
                for(int j=0;j<row.getLastCellNum();j++) {
                    Cell cell = row.getCell(j, Row.CREATE_NULL_AS_BLANK);
                    switch (cell.getCellType()) {
                    case Cell.CELL_TYPE_BLANK:
                        
                        break;
                    case Cell.CELL_TYPE_BOOLEAN:
                       
                        break;
                    case Cell.CELL_TYPE_NUMERIC:
                        // 数值
                        
                        break;
                    case Cell.CELL_TYPE_STRING:
                        if (i != 0) {
                            String valueStr = cell.getStringCellValue();
                            if (j == 7) {
                                //登录名
                                user.setUserLoginNameHY(valueStr);
                            }else if (j == 9) {
                                //身份证
                                user.setUserCardEncryptionHY(valueStr);
                            }
                        }
                        break;
                    case Cell.CELL_TYPE_ERROR:
                        
                        break;
                    default:
                        break;
                    }
                }
                if (i!=0) {
                    userExcel.add(user);
                }
                
            }
View Code

相关文章: