Skip to content

Commit

Permalink
✨ 优化 StreamUtilsEx
Browse files Browse the repository at this point in the history
  • Loading branch information
SenhLinsh committed Jun 6, 2020
1 parent 5ac7d48 commit 49f5d76
Showing 1 changed file with 55 additions and 7 deletions.
62 changes: 55 additions & 7 deletions uee/src/main/java/com/linsh/lshutils/utils/StreamUtilsEx.java
Original file line number Diff line number Diff line change
@@ -1,9 +1,15 @@
package com.linsh.lshutils.utils;

import com.linsh.utilseverywhere.StringUtils;

import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;

/**
* <pre>
Expand All @@ -15,26 +21,35 @@
*/
public class StreamUtilsEx {

public static String getText(InputStream inputStream) {
/**
* 获取流中的文本
*
* @param inputStream 输入流
*/
public static String getText(InputStream inputStream) throws IOException {
return getText(inputStream, "UTF-8");
}

public static String getText(InputStream inputStream, String charsetName) {
/**
* 获取流中的文本
*
* @param inputStream 输入流
* @param charsetName 字符集
*/
public static String getText(InputStream inputStream, String charsetName) throws IOException {
StringBuilder fileContent = new StringBuilder();
BufferedReader reader = null;
try {
InputStreamReader is = new InputStreamReader(inputStream, charsetName);
reader = new BufferedReader(is);
String line = null;
String line;
while ((line = reader.readLine()) != null) {
if (!fileContent.toString().equals("")) {
fileContent.append("\r\n");
if (fileContent.length() == 0) {
fileContent.append(StringUtils.lineSeparator());
}
fileContent.append(line);
}
return fileContent.toString();
} catch (IOException e) {
return null;
} finally {
if (reader != null) {
try {
Expand All @@ -45,4 +60,37 @@ public static String getText(InputStream inputStream, String charsetName) {
}
}
}

/**
* 将输入流写入文件
*
* @param inputStream 输入流
* @param file 文件
* @return 是否写入成功
*/
public static void saveToFile(InputStream inputStream, File file) throws IOException {
if (inputStream == null)
throw new IllegalArgumentException("inputStream == null");
File dir = file.getParentFile();
if (dir != null && !dir.exists()) {
dir.mkdirs();
}
OutputStream os = null;
try {
os = new BufferedOutputStream(new FileOutputStream(file, false));
byte[] data = new byte[8192];
int len;
while ((len = inputStream.read(data, 0, data.length)) != -1) {
os.write(data, 0, len);
}
} finally {
try {
inputStream.close();
} finally {
if (os != null) {
os.close();
}
}
}
}
}

0 comments on commit 49f5d76

Please sign in to comment.