java 字串與檔案相互轉換

殷長慶發表於2020-09-29

	/**
	* Prints some data to a file using a BufferedWriter
	*/
	private void writeToFile(File file, String txt) {

		BufferedWriter bufferedWriter = null;

		try {

			// Construct the BufferedWriter object
			bufferedWriter = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), "UTF-8"));

			// Start writing to the output stream
			bufferedWriter.write(txt);

		} catch (FileNotFoundException ex) {
			ex.printStackTrace();
		} catch (IOException ex) {
			ex.printStackTrace();
		} finally {
			// Close the BufferedWriter
			if (bufferedWriter != null) {
				try {
					bufferedWriter.flush();
					bufferedWriter.close();
				} catch (IOException ex) {
					ex.printStackTrace();
				}
			}
		}
	}

	public String fileToText(HttpServletRequest request, String pathname) {

		if (null == request) {
			request = this.request;
		}

		String contextPath = request.getServletContext().getRealPath("");

		File file = new File(contextPath + pathname);
		if (!file.exists()) {
			return "";
		}
		return fileToString(file);
	}

	/**
	* Prints some data to a file using a BufferedWriter
	*/
	private String fileToString(File file) {

		BufferedReader bufferedReader = null;

		StringBuffer buffer = new StringBuffer();

		try {

			bufferedReader = new BufferedReader(new InputStreamReader(new FileInputStream(file), "UTF-8"));
			while (bufferedReader.readLine() != null) {
				buffer.append(bufferedReader.readLine());
			}

		} catch (FileNotFoundException ex) {
			ex.printStackTrace();
		} catch (IOException ex) {
			ex.printStackTrace();
		} finally {
			if (bufferedReader != null) {
				try {
					bufferedReader.close();
				} catch (IOException ex) {
					ex.printStackTrace();
				}
			}
		}
		return buffer.toString();
	}

 

相關文章