免费行情软件app网站大全下载u288,济南网站建设老威,怎么自己制作app,网站建设 设计业务范围这篇文章的主要原因是尝试不重复自己#xff08; DRY #xff09;#xff0c;因为通常#xff0c;我会遇到读写压缩和非压缩文件#xff08;主要是JSON和CSV#xff09;的递归需求。 首先让我们看看如何读取文本文件。 注意我正在使用#xff08;相对较小的#xff09… 这篇文章的主要原因是尝试不重复自己 DRY 因为通常我会遇到读写压缩和非压缩文件主要是JSON和CSV的递归需求。 首先让我们看看如何读取文本文件。 注意我正在使用相对较小的文本文件因此 read方法返回一个包含全部内容的String。 我正在使用BufferedReader逐行读取。 private String readFile(String fileName) {StringBuilder sb new StringBuilder();try {BufferedReader input new BufferedReader(new FileReader(new File(fileName)));try {String line null;while ((line input.readLine()) ! null) {sb.append(line);}} finally {input.close();}} catch (IOException ex) {// Handle exceptionreturn null;}return sb.toString();
} 注意做事的方法不只一种。 在条目读取文本文件的最佳方式中 您可以找到许多不同的方法来读取文本文件具体取决于您的JDK版本和文件大小。 类似于将String写入文件 private void writeFile(String fileName, String value) {try {FileWriter fw new FileWriter(fileName);BufferedWriter bw new BufferedWriter(fw);bw.write(value);bw.close();} catch (IOException ex) {// Handle exception}
} 要读取/写入带有二进制数据的压缩文件我们需要使用流和缓冲区。 因此要读取GZIP压缩文件并获取字符串 private String readCompressedFile(String fileName) {try {GZIPInputStream gis new GZIPInputStream(new FileInputStream(fileName));ByteArrayOutputStream fos new ByteArrayOutputStream();byte[] buffer new byte[1024];int len;while ((len gis.read(buffer)) ! -1) {fos.write(buffer, 0, len);}fos.close();gis.close();return new String(fos.toByteArray());} catch (IOException ex) {// Handle exceptionreturn null;}
} 并类似地将字符串写入GZip压缩文件 private void writeCompressedFile(String fileName, String value) {try {InputStream is new ByteArrayInputStream(value.getBytes());GZIPOutputStream gzipOS new GZIPOutputStream(new FileOutputStream(fileName));byte[] buffer new byte[1024];int len;while ((len is.read(buffer)) ! -1) {gzipOS.write(buffer, 0, len);}gzipOS.close();is.close();} catch (IOException ex) {// Handle exception}
}资源资源 接下来您可以找到几个适用于各种JDK版本的Java代码的重要链接 读写文本文件 读写二进制文件 翻译自: https://www.javacodegeeks.com/2015/01/readingwriting-compressed-and-not-compressed-files-in-java.html