采用Servlet方法,获取文件内容位置,读四行???退一行???这个针对一个文件没什么大问题,要是多个文件呢?出现其他情况呢?有没有靠谱一点的方法。。。试了一下用正则表达式可以提取上传多个文本文件的内容,用正则表达式就要用字符流,然后就不知道怎么处理字节形式的图片内容,出现了编码的问题。伤心。 _(:3 」∠)_
//获取临时文件输入流 FileInputStream in = new FileInputStream(tempFile); InputStreamReader reader = new InputStreamReader(in); BufferedReader br = new BufferedReader(reader); //将输入流数据存到字符串中 StringBuffer sb = new StringBuffer(); String result = ""; String content; String temp = br.readLine(); while((content = br.readLine()) != null) { sb.append(content + "\r\n"); } result = sb.toString(); System.out.println(result); br.close(); //将保存有多个文件信息的字符串分割为多块 String[] items = result.split(temp); for (String item : items) { //获取文件名并创建文件 String regexOfFileName = "filename=\"([^\"]*)"; Pattern patternOfFileName = Pattern.compile(regexOfFileName); Matcher matcherOfFileName = patternOfFileName.matcher(item); String fileName = ""; FileWriter out = null; if(matcherOfFileName.find()) { fileName = matcherOfFileName.group(1); System.out.println(fileName); File saveFile = new File(path, fileName); out = new FileWriter(saveFile); } //获取文件内容并保存 String regexOfFileData = "Content-Type[^\n]*[\r\n]*([\\s\\S]*)"; Pattern patternOfFileData = Pattern.compile(regexOfFileData); Matcher matcherOfFileData = patternOfFileData.matcher(item); String fileData = ""; if(matcherOfFileData.find()) { fileData = matcherOfFileData.group(1); fileData = fileData.substring(0, fileData.length() - 2); System.out.println(fileData); out.write(fileData); out.close(); } }
试试看把字符拆成字节来读,然后自己再写代码解析出字符也是可以的试试用URLDecode解码试试,注意编码一致性
换了一种方法,可以处理多个文件,可以是文本,可以是图片或者其他。
//读取临时文件 RandomAccessFile randomOfTempFile = new RandomAccessFile(tempFile, "r"); //temp为post请求内容分隔符 String temp = randomOfTempFile.readLine(); String content; while((content = randomOfTempFile.readLine()) != null) { //解决中文文件名乱码问题 content = new String(content.getBytes("ISO-8859-1"), "utf-8"); if(content.contains("filename")) { System.out.println(content); //获取文件名 String regexOfFileName = "filename=\"([^\"]*)"; Pattern patternOfFileName = Pattern.compile(regexOfFileName); Matcher matcherOfFileName = patternOfFileName.matcher(content); String fileName = ""; File saveFile = null; if(matcherOfFileName.find()) { fileName = matcherOfFileName.group(1); System.out.println(fileName); saveFile = new File(path, fileName); } //获取文件内容起始结束位置 randomOfTempFile.readLine(); randomOfTempFile.readLine(); long startPosition = randomOfTempFile.getFilePointer(); long endPosition; while(true) { endPosition = randomOfTempFile.getFilePointer(); String tempStr = randomOfTempFile.readLine(); if (tempStr != null && tempStr.contains(temp)) { break; } } //保存文件 randomOfTempFile.seek(startPosition); RandomAccessFile randomOfSaveFile = new RandomAccessFile(saveFile, "rw"); while(startPosition < endPosition){ randomOfSaveFile.write(randomOfTempFile.readByte()); startPosition = randomOfTempFile.getFilePointer(); } randomOfSaveFile.close(); } } randomOfTempFile.close();