⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 fileprocessor.java

📁 该程序实现java语言对文件系统的统一处理
💻 JAVA
📖 第 1 页 / 共 2 页
字号:
 *					useSrcFileType 是否使用原文件扩展名
 * 返回/return:		N/A
 * 步骤/steps :		1、读取输入流
 *					2、读取分割字符
 *					3、分解参数直到参数流结束
 * 修改记录/Revision
 ************************************************************************************/
public void parseHttpStream(javax.servlet.http.HttpServletRequest req) throws Exception {
	byte[] bBuf = new byte[BUF_SIZE];
	String aLine;
	String dataSeparator; //参数分割符
	String parameterName = "";
	String parameterValue = "";
	String uploadSrcFileName = "";
	String uploadFileName = "";
	String uploadFileType = "";
	Integer uploadFileSize = null;
	boolean contentNotParse, noFileType, isUploadFile;
	int streamSize;
	int byteRead = 0, totalBytes = 0;
	int totalFileBytes;
	int index;

	//判断req类型
	String sType = req.getContentType();
	if (sType != null)
		sType = sType.trim();
	if ((sType == null) || (!sType.startsWith(MULTIDATATYPE)))
		throw new Exception(this.REQUEST_TYPE_ERROR);

	//读取输入流
	javax.servlet.ServletInputStream is = req.getInputStream();
	streamSize = req.getContentLength();

	//读取分割字符
	try {
		byteRead = is.readLine(bBuf, 0, BUF_SIZE);
	} catch (IOException e) {
		throw new Exception(READLINE_IOEXCEPTION);
	}
	totalBytes += byteRead;
	aLine = new String(bBuf, 0, byteRead);
	dataSeparator = aLine.substring(0, aLine.length() - 2);

	//分解参数直到参数流结束
	int fileno = 0;
	while (streamSize > totalBytes) {

		//读取参数第一行
		try {
			byteRead = is.readLine(bBuf, 0, BUF_SIZE);
		} catch (IOException e) {
			throw new Exception(READLINE_IOEXCEPTION);
		}
		totalBytes += byteRead;
		aLine = null;
		aLine = new String(bBuf, 0, byteRead);
		isUploadFile = false;
		if (byteRead > NAME_STRING.length()) {
			if ((aLine.substring(0, NAME_STRING.length())).equals(NAME_STRING)) {
				//读取参数名
				index = aLine.indexOf("\"", NAME_STRING.length());
				parameterName = aLine.substring(NAME_STRING.length(), index);

				//如果为文件
				index = aLine.indexOf(FILENAME_STRING, index);
				if (index >= 0) {
					//读取文件名
					isUploadFile = true;
					uploadSrcFileName = aLine.substring(index + FILENAME_STRING.length(), aLine.indexOf("\"", index + FILENAME_STRING.length())).trim();
				} else {
					isUploadFile = false;
				}
			} else {
				// 如果第一行不符合规范,抛出错误
				throw new Exception(CORRUPTED_INPUT_STREAM);
			}
		}

		//读取参数第二行
		try {
			byteRead = is.readLine(bBuf, 0, BUF_SIZE);
		} catch (IOException e) {
			throw new Exception(READLINE_IOEXCEPTION);
		}
		totalBytes += byteRead;

		//上载文件第二行为文件类型说明
		//一般参数第二行为空行

		//处理上载文件类型,生成uploadFileName
		if (isUploadFile) {
			if ((uploadSrcFileName == null) || uploadSrcFileName.equals("")) {

				//上载文件为空
				uploadFileType = "";
				uploadFileSize = new Integer(0);
				uploadFileName = "";

				//忽略其他内容和空行
				contentNotParse = true;
				do {
					try {
						byteRead = is.readLine(bBuf, 0, BUF_SIZE);
					} catch (IOException e) {
						throw new Exception(READLINE_IOEXCEPTION);
					}
					totalBytes += byteRead;
					aLine = new String(bBuf, 0, byteRead);
					//处理读取的是分割字符串
					if (aLine.length() >= dataSeparator.length()) {
						if (aLine.substring(0, dataSeparator.length()).equals(dataSeparator)) {
							contentNotParse = false;
						}
					}
				} while (contentNotParse);
			} else {
				//读取文件类型
				aLine = new String(bBuf, 0, byteRead);
				if (byteRead > CONTENT_TYPE_STRING.length())
					if ((aLine.substring(0, CONTENT_TYPE_STRING.length())).equals(CONTENT_TYPE_STRING))
						uploadFileType = aLine.substring(CONTENT_TYPE_STRING.length(), aLine.length()).trim();
					else
						uploadFileType = "";
				else
					uploadFileType = "";

			//读取下一空行
			try {
				byteRead = is.readLine(bBuf, 0, BUF_SIZE);
			} catch (IOException e) {
				throw new Exception(READLINE_IOEXCEPTION);
			}
			totalBytes += byteRead;

			// 检查上载目录,如不存在建立目录
			String tmpdir = getFileSavePath();
			File dir = new File(tmpdir);
			if (dir.isFile()) {
				throw new Exception(WORKING_DIR_IS_FILE);
			} else
				if (!dir.exists()) {
					if (!dir.mkdirs()) {
						throw new Exception(WORKING_DIR_CREATE_ERROR);
					}
				}

				// 建立上载文件
			fileno++;
			FileOutputStream fileOut = null;
			try {
				String s = String.valueOf(fileno);
				while (s.length() < 4)
					s = '0' + s;
				uploadFileName = tmpdir + fileNamePrefix + System.currentTimeMillis() + s;
				//uploadFileName = tmpdir + uploadSrcFileName + System.currentTimeMillis() + s;
				
				if (holdOrgFileType) {
					int j = uploadSrcFileName.lastIndexOf('.');
					if (j > 0) {
						s = uploadSrcFileName.substring(j, uploadSrcFileName.length());
						uploadFileName += s;
					};
				} else
					uploadFileName += "." + fileType;
				fileOut = new FileOutputStream(uploadFileName);
			} catch (IOException e) {
				throw new Exception(FILE_OUTPUT_STREAM_IOEXCEPTION);
			}

			//读取上载文件
			totalFileBytes = 0;
			contentNotParse = true;
			boolean sign = false;
			byte lineEnd1 = 0, lineEnd2 = 0;
			do {
				try {
					byteRead = is.readLine(bBuf, 0, BUF_SIZE);
				} catch (IOException e) {
					throw new Exception(READLINE_IOEXCEPTION);
				}
				totalBytes += byteRead;
				totalFileBytes += byteRead;
				aLine = null;
				try {
					if (byteRead > 0)
						aLine = new String(bBuf, 0, byteRead);
				} catch (Exception e) {
					if (byteRead > 0)
						aLine = "";
				}

				//处理读取的是分割字符串,或结束字符串
				if (aLine.length() >= dataSeparator.length()) {
					if (aLine.substring(0, dataSeparator.length()).equals(dataSeparator)) {
						try {
							fileOut.close();
						} catch (IOException e) {
							throw new Exception(CLOSE_IOEXCEPTION);
						}
						totalFileBytes -= byteRead;
						totalFileBytes -= 2;
						uploadFileSize = new Integer(totalFileBytes);
						contentNotParse = false;
					}
				}

				//处理读取的是内容
				if (contentNotParse == true) {
					try {
						//将上一行保留的字节写入文件
						if (sign) {
							fileOut.write(lineEnd1);
							fileOut.write(lineEnd2);
						}
						//保留这一行最后两个字节
						if (byteRead >= 2) {
							lineEnd1 = bBuf[byteRead - 2];
							lineEnd2 = bBuf[byteRead - 1];
							fileOut.write(bBuf, 0, byteRead - 2);
							sign = true;
						} else {
							lineEnd1 = 0;
							lineEnd2 = 0;
							fileOut.write(bBuf, 0, byteRead);
							sign = false;
						}
					} catch (IOException e) {
						throw new Exception(WRITE_IOEXCEPTION);
					}
				}
			} while (contentNotParse && (streamSize > totalBytes)); // end of do while (contentNotParse)
		} //end of else ( uploadsrfilename is not empty)

		uploadParameterNames.addElement(parameterName);
		uploadSrcFileNames.addElement(uploadSrcFileName);
		uploadFileNames.addElement(uploadFileName);
		uploadFileTypes.addElement(uploadFileType);
		uploadFileSizes.addElement(uploadFileSize);
	} else {
		//处理不是一上载文件,而是一般参数

		// 读取参数值
		contentNotParse = true;
		parameterValue = "";
		do {
			try {
				byteRead = is.readLine(bBuf, 0, BUF_SIZE);
			} catch (IOException e) {
				throw new Exception(READLINE_IOEXCEPTION);
			}
			totalBytes += byteRead;
			aLine = null;
			aLine = new String(bBuf, 0, byteRead);
			if (aLine.length() >= dataSeparator.length()) {
				if (aLine.substring(0, dataSeparator.length()).equals(dataSeparator)) {
					contentNotParse = false;
				}
			}
			if (contentNotParse) {
				parameterValue += aLine.substring(0, aLine.length());
			}
		} while (contentNotParse && (streamSize > totalBytes));
		parameterValue = parameterValue.substring(0, parameterValue.length() - 2);
		//System.out.println(parameterValue);
		parameterNames.addElement(parameterName);
		parameterValues.addElement(parameterValue);
	}
} // end while (streamSize > totalBytes)
} // end of MultiDataFormParser()           
/**
 * 该方法释放所有列表对象
 */
public void release() {
	uploadParameterNames.removeAllElements();
	uploadSrcFileNames.removeAllElements();
	uploadFileNames.removeAllElements();
	uploadFileTypes.removeAllElements();
	uploadFileSizes.removeAllElements();
	parameterNames.removeAllElements();
	parameterValues.removeAllElements();
}
public void setFileNamePrefix(String newValue) {
	this.fileNamePrefix = newValue;
}
public void setFileType(String newValue) {
	this.fileType = newValue;
}
public void setHoldOrgFileType(boolean newValue) {
	this.holdOrgFileType = newValue;
}
public void setRelativePath(String newValue) {
	this.relativeFilePath = validFilePath(newValue);
	this.relativeURLPath = validURLPath(newValue);
}
public void setRootPath(String newValue) {
	this.rootPath = validFilePath(newValue);
}
public void setRootURLPath(String newValue) {
	this.rootURLPath = validURLPath(newValue);
}
/************************************************************************************
 * 功能/function:	返回符合物理文件系统的路径字符串
 * 参数/parameter:	path--需要检验的路径字符串
 * 返回/return:		符合物理文件系统的路径字符串
 * 步骤/steps :		1、替换所有路径分割符
 *					2、检验末尾的路径分割符号
 * 修改记录/Revision
 ************************************************************************************/
public String validFilePath(String path) {
	if ((path==null)||(path.trim().equals("")))	return "";
	else{
		//1、替换所有文件分割符 '/' 为 物理文件分割符
		StringBuffer temp = new StringBuffer(path) ;
		for(int i=0;i<temp.length();i++){
			if (temp.charAt(i)=='/') temp.setCharAt(i,File.separatorChar);
		}

		//2、检验路径最后的文件分割符
		char c = temp.charAt(path.length()-1);
		if (c != File.separatorChar) temp.append(File.separatorChar);
		return temp.toString();
	}
}
/************************************************************************************
 * 功能/function:	返回符合URL格式的路径字符串
 * 参数/parameter:	path--需要检验的路径字符串
 * 返回/return:		符合URL格式的路径字符串
 * 步骤/steps :		1、替换所有路径分割符
 *					2、检验末尾的路径分割符
 * 修改记录/Revision
 ************************************************************************************/
public String validURLPath(String path) {
	if ((path==null)||(path.trim().equals("")))	return "";
	else{
		//1、替换所有物理文件分割符为 '/'
		StringBuffer temp = new StringBuffer(path) ;
		for(int i=0;i<temp.length();i++){
			if (temp.charAt(i) == File.separatorChar) temp.setCharAt(i,'/');
		}

		//2、检验路径最后的分割符'/'
		char c = temp.charAt(path.length()-1);
		if (c != '/') temp.append('/');
		return temp.toString();
	}
}
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -