javaIO文件读写操作处理文件乱码

  获得文件大小,可以进行文件大小的判断。

public void getFileLength(){
	String str = "D:\\testPath\\testFile.txt";
  	File file = new File(str);
  	FileInputStream fis;
  	try {
     		fis = new FileInputStream(file);
      		System.out.println("文件size:"+String.valueOf(fis.available()/1024/1024)+"M");
  	} catch (FileNotFoundException e) {
      		e.printStackTrace();
  	} catch (IOException e) {
      		e.printStackTrace();
  	}
}

  

 

  文件乱码处理:读写操作时添加编码格式。

    读文件,把一个大文件拆成小文件

  public LogLockFile split(File file) throws IOException {
	BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(file), "UTF-8"));
	while ((txt = reader.readLine()) != null) {
            		if ("" == txt.trim() || "".equals(txt.trim()) || txt.trim() == null) {
                 		continue;
              		}
             		// 去#开头的行和空行
            	if (!"".equals(txt) && txt != null) {
                  		if (txt.indexOf("#") == 0) {
                      		   continue;
                 		}
               			list.add(txt);
                		n++;
             		}
           		if (n == DEFAULT_FILE_LENGTH) {//满足长度写入文件
                   		writerFile(list, logLockFile.getPath(), tempName + getStringFill(page) + "." + tempType);
                   		n = 0;
                 		page++;
                  		list = new ArrayList<String>();
             		 }
       	}
   }

 

 

    写文件方法

private void writerFile(List<String> list, String path, String name) {
        try {
	File f = new File(path + "\\" + name);
   	BufferedWriter output = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(f), "utf-8"));
   	for (int i = 0; i < list.size(); i++) {
   		String str = list.get(i);
   		if (str == null) {
   			 break;
   		 }
 		 output.write(str);
 		 output.write("\r\n");
 	}
  	output.close();
       } catch (Exception e) {
   	e.printStackTrace();
       }
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值