java中file转字符串,字符串输出为文件

 读取文件转为字符串:

 
//输入文件File类型,输出字符串
	public static String fileToString(File file) {
		InputStream is = null;
		ByteArrayOutputStream bos = new ByteArrayOutputStream();
		byte[] buffer = new byte[1024];
		int temp = -1;
		try {
			is = new FileInputStream(file);
			while ((temp = is.read(buffer)) != -1) {
				bos.write(buffer, 0, temp);
			}
			return bos.toString();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if(is!=null) {
					is.close();
				}
				if(bos != null) {
					bos.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return null;
	}

  

字符串输出为文件

 
// 字符串输出为文件的方法
	// 参数为要输出为文件的字符串,输出路径,及文件名
	public static boolean stringToFile(String fileContent, String outPath, String fileName) {
		boolean result = false;
		File file = new File(outPath, fileName);
		OutputStream os = null;
		try {
			if (!file.exists()) {
				file.createNewFile();
			}
			os = new FileOutputStream(file);
			os.write(fileContent.getBytes());
			os.flush();
			result = true;
 
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if(os!=null) {
					os.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
 
		return result;
	}

  原文:https://www.cnblogs.com/cxylm/p/15090320.html

 

posted @ 2024-02-19 20:08  小宁同学柠檬茶  阅读(98)  评论(0编辑  收藏  举报