文件复制
1 使用IO复制
public static void ioCopy(String pathIn,String pathOut) throws IOException {
BufferedInputStream inputStream = new BufferedInputStream(new FileInputStream(pathIn));
BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(pathOut));
int len = 0;
byte[] buffer = new byte[1024];
while ((len = inputStream.read(buffer)) != -1) {
outputStream.write(buffer,0,len);
}
inputStream.close();
outputStream.close();
}
2 使用NIO复制
public static void channelCopy(String pathIn, String pathOut) throws IOException {
FileChannel fcIn = new FileInputStream(pathIn).getChannel(),
fcOut = new FileOutputStream(pathOut).getChannel();
fcIn.transferTo(0, fcIn.size(), fcOut);
fcIn.close();
fcOut.close();
}
向文件中写入字符
1 用Writer向文件中写入字符串
/**
* @param content
* @param path
* @return void
* @desc 用Writer向文件中写入字符串
* @method stringToFileByWriter
* @author YulinChen
* @date 2020/2/13 20:12
*/
public static void stringToFileByWriter(String content, String path) throws IOException {
PrintWriter writer = new PrintWriter(new File(path));
writer.print(content);
writer.close();
}
2 用Channel向文件中写入字符串
/**
* @param content
* @param path
* @return void
* @desc 用Channel向文件中写入字符串
* @method stringToFileByChannel
* @author YulinChen
* @date 2020/2/13 20:12
*/
public static void stringToFileByChannel(String content, String path) throws IOException {
FileChannel channel = new FileOutputStream(path).getChannel();
//FileChannel channel = new RandomAccessFile(path, "rw").getChannel();
channel.write(ByteBuffer.wrap(content.getBytes("UTF-8")));
channel.close();
}
从输入中获取字符串
1 从流中获取字符串
/**
* @param in 输入流
* @return java.lang.String
* @desc 从流中获取字符串
* @method getString
* @author YulinChen
* @date 2020/2/13 19:49
*/
public static String getString(InputStream in) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(in, "UTF-8"));
StringBuilder sb = new StringBuilder();
for (String line = reader.readLine(); line != null; line = reader.readLine()) {
sb.append(line).append("
");
}
reader.close();
return sb.toString();
}
2 从Channel中获取字符串
中文乱码,不推荐