下面经过FileChannel向文件中输入数据的一个例子
public static void saveFileChannel(String str, File toFile,String fileName) {
FileOutputStream outputStream = null;
FileChannel channel = null;
if(!toFile.exists() && !toFile.isDirectory()){
toFile.mkdir();
}
try {
outputStream = new FileOutputStream(toFile+"/" + fileName);
channel = outputStream.getChannel();
ByteBuffer buffer = ByteBuffer.allocate(1024);
buffer.put(str.getBytes());
buffer.flip();
while (buffer.hasRemaining()) channel.write(buffer);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (channel != null) {
channel.close();
}
if (outputStream != null) {
outputStream.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
这个是经过FileChannel进行文件的复制
public static void fileCopyWithFileChannel(File fromFile, File toFile) {
FileInputStream fileInputStream = null;
FileOutputStream fileOutputStream = null;
FileChannel fileChannelInput = null;
FileChannel fileChannelOutput = null;
if(!toFile.exists() && !toFile.isDirectory()){
toFile.mkdir();
}
try {
fileInputStream = new FileInputStream(fromFile);
fileOutputStream = new FileOutputStream(toFile+"/"+fromFile.getName());
fileChannelInput = fileInputStream.getChannel();
fileChannelOutput = fileOutputStream.getChannel();
fileChannelInput.transferTo(0, fileChannelInput.size(), fileChannelOutput);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (fileInputStream != null)
fileInputStream.close();
if (fileChannelInput != null)
fileChannelInput.close();
if (fileOutputStream != null)
fileOutputStream.close();
if (fileChannelOutput != null)
fileChannelOutput.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
这里是经过BufferedWriter写入数据的
public synchronized static void saveFile(Object str, File toFile,String fileName){
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String date = format.format(new Date());
if (!toFile.exists() && !toFile.isDirectory()) {
toFile.mkdir();
}
BufferedWriter out = null;
try {
out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(toFile + "/" + fileName, true),"UTF-8"));
out.newLine();
out.write(date + ":" + str);
out.flush();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (out != null) {
out.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
这里是执行的main方法
public static void main(String[] args) throws IOException {
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
String date = format.format(new Date());
String string = "hello";
File toFile = new File("E:/IdeaProject/T");
saveFileChannel(string, toFile,date+".txt");
File file = new File("E:/IdeaProject/TEXT/DATA.txt");
fileCopyWithFileChannel(file, toFile);
saveFile(string, toFile,"demo.txt");
}