excel或csv导入,第一个空格转换异常问题处理

本文介绍了一种处理CSV文件的方法,特别关注如何解决读取空字符串时出现的问题,并提供了具体的Java代码实现,包括文件转码、异常处理及空字符串的正确识别。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

该方法是通过读取文件所在地址,start是读取的起始行数默认1,由于bufferReader在readL:ine()读取第一行数据的时候会出现解析""空字符串错误。所以导致在程序中出现这种错误——两个在从肉眼上进行比较两个相同的空串,第一个空串返回false,然后用String lenth() 方法返回1,此时表明导入时读取文件的空字符串不是真正意义上的空字符,导入文件是csv格式 ,需用文本打开,在读取本地文件的时候对其进行了转码,判断位于行的第一个字符是否等于65279 ,如果相等从第二个字符截取即可。

File file = new File(path);
public static List<Map<Integer, String>> read(File file, int start)throws OperateSystemException{
		if (!file.getName().toUpperCase().endsWith(".CSV")){
			return null;
		}
		BufferedReader reader = null;
		InputStreamReader fReader = null;

		try {
			fReader = new InputStreamReader(new FileInputStream(file),"UTF-8");
			List<Map<Integer, String>> list = new ArrayList<>();
			reader = new BufferedReader(fReader);
			int n = 0;
			start = start < 1 ? 1: start;
			String line;
			String[] temp;
			Map<Integer, String> map ;
			while ((line = reader.readLine()) != null) {
				if (++n < start){
					continue;
				}
				if (StringUtil.isEmpty(line)) {
					continue;
				}
				temp = readLine(line);
				if (temp == null){
					continue;
				}

				map= new HashMap<>();
				for (int i = 0; i < temp.length; i++) {
					if(temp[i].trim().length()>0){
						char c = temp[i].trim().charAt(0);
						if (c == 65279) {
							temp[i] =temp[i].substring(1);
						}
					}


					map.put(i+1, temp[i]);
				}
				list.add(map);
			}
			return list;
		}catch (FileNotFoundException e){
			e.printStackTrace();
			ThrowUtil.error(OperateSystemErrorCode.MODULES_CSVUTILS_UPLOAD__FILE_NOT_FOUND);
		}
		catch (Exception e) {
			e.printStackTrace();
			ThrowUtil.error(OperateSystemErrorCode.MODULES_CSVUTILS_UPLOAD__IO_EXCEPTION);
			return null;
		} finally {
			try {
				if (reader != null) {
					reader.close();
					reader = null;
				}
			} catch (IOException e2) {
				e2.printStackTrace();
				ThrowUtil.error(OperateSystemErrorCode.MODULES_CSVUTILS_UPLOAD__IO_EXCEPTION);
			}
		}

		return null;
	}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值