一、对文件读取的例子
package org.example;
import javax.crypto.SecretKey;
import java.io.*;
/**
* Created with IntelliJ IDEA.
*
* @author : Future master
* @version : 1.0
* @Project : TestThree
* @Package : org.example
* @ClassName : GetAes.java
* @createTime : 2021/11/24 23:09
* @Email : 2467636181@qq.com
*/
public class InReader {
//读取一个目录下的所有文件的内容并且返回一个字符串数组
public String[] getFiles(File file) throws IOException {
String[] strings = null;
if(file.isDirectory()){
File[] files = file.listFiles();
strings = new String[files.length];
for(int i = 0;i<files.length;i++){
strings[i] = getFile(files[i]);
}
}
return strings;
}
//读取一个文件中的内容并且返回一个字符串
public String getFile(File file) throws IOException {
String str1 = null;
if (file.isFile()){
int length = new Long(file.length()).intValue();
char[] content = new char[length];
InputStream input = new FileInputStream(file);
Reader reader = new InputStreamReader(input,"UTF-8");
int len = reader.read(content);
str1 = new String(content,0,len);
reader.close();
input.close();
}
return str1;
}
//利用字节流对文件进行一个读取,返回字节数组
public byte[] getFileByte(File file) throws IOException {
byte[] bytes = null;
if(file.isFile()){
int length = new Long(file.length()).intValue();
bytes = new byte[length];
InputStream input = new FileInputStream(file);
input.read(bytes);
input.close();
}
return bytes;
}
//读取一个目录下的所有文件名,并且返回一个字符串数组
public String[] getFileName(File file){
String[] names = null;
if(file.isDirectory()){
File[] files = file.listFiles();
names = new String[files.length];
for(int i = 0;i<files.length;i++){
names[i] = files[i].getName();
}
}
return names;
}
}
二、对文件进行写入(利用字节流)的例子
package org.example;
import java.io.*;
/**
* Created with IntelliJ IDEA.
*
* @author : Future master
* @version : 1.0
* @Project : TestThree
* @Package : org.example
* @ClassName : OutWriter.java
* @createTime : 2021/11/24 23:48
* @Email : 2467636181@qq.com
*/
public class OutWriter {
public void outWrite(byte[] content,File file) throws IOException {
if(file.isFile()){
OutputStream out = new FileOutputStream(file);
BufferedOutputStream bufferOut = new BufferedOutputStream(out);
bufferOut.write(content);
bufferOut.flush();
bufferOut.close();
out.close();
}
}
}