看书,看视频理解的东西不是真正的学会,通过经常的联系后的惯性思维才是。
目录
图片用BASE64Encoder编码,BASE64Decoder解码
File简单应用
public static void test() throws IOException {
File file = new File(".");
//直接获取文件名,输出一点
System.out.println(file.getName());
//获取相对路径的负路径可能出错,下面代码输出null
System.out.println(file.getParent());
//获取绝对路径
System.out.println(file.getAbsoluteFile());
//获取上一级路径
System.out.println(file.getAbsoluteFile().getParent());
//创建临时文件
File temFile = File.createTempFile("aaa", ".txt", file);
//指定当JVM退出是删除该文件
temFile.deleteOnExit();
File newFile = new File(System.currentTimeMillis() + "");
System.out.println("newFile对象是否存在:" + newFile.exists());
//创建个文件
newFile.createNewFile();
//创建个文件夹
newFile.mkdir();
//列出当前路径下的所有文件和路径
String[] fileList = file.list();
System.out.println("===当前路径下所有文件和路径如下===");
for (String fileName : fileList) {
System.out.println(fileName);
}
//列出所有的磁盘根路径
File[] roots = File.listRoots();
System.out.println("====系统所有根路径如下====");
for (File root : roots) {
System.out.println(root);
}
}
File列出某个文件夹下所有的文件
public static void main(String[] args) {
listAllFiles(new File("."));
}
/**
* 迭代列出某个文件夹下所有的文件
* @param dir
*/
public static void listAllFiles(File dir) {
if (dir == null || !dir.exists()) {
return;
}
if (dir.isFile()) {
System.out.println(dir.getName());
return;
}
File[] files = dir.listFiles();
for (File file : files) {
listAllFiles(file);
}
}
通过FilenameFilter过滤文件
public static void fileNameFilter() {
File file = new File(".");
String[] nameList = file.list(((dir, name) -> name.endsWith(".java") || new File(name).isDirectory()));
for (String name : nameList) {
System.out.println(name);
}
}
File复制磁盘文件
public static void copyFile(String src, String dist) throws IOException {
FileInputStream in = new FileInputStream(src);
FileOutputStream out = new FileOutputStream(dist);
byte[] buffer = new byte[20 * 1024];
int cnt;
/**
* read()最多读取buffer.length个字节
* 返回的实际读取的个数
* 返回-1的时候表示读到eof,即文件尾
*/
while ((cnt = in.read(buffer)) != -1) {
out.write(buffer, 0, cnt);
}
in.close();
out.close();
}
Buffered流更快
BufferedInputStream带来的速度提升,准备文件几十兆,太小看不出明显效果,太大等的时间太长了。我准备的是个16m的视频文件。
public static void copyFile(String src, String dist) throws IOException {
long start2 = System.currentTimeMillis();
FileInputStream in = new FileInputStream(src);
FileOutputStream out = new FileOutputStream(dist);
byte[] buffer = new byte[20 * 1024];
int cnt;
/**
* read()最多读取buffer.length个字节
* 返回的实际读取的个数
* 返回-1的时候表示读到eof,即文件尾
*/
while ((cnt = in.read(buffer)) != -1) {
out.write(buffer, 0, cnt);
}
in.close();
out.close();
long end2 = System.currentTimeMillis();
System.out.println("不用缓存类时用的时间:" + (end2 - start2));
long start3 = System.currentTimeMillis();
FileInputStream in2 = new FileInputStream(src);
FileOutputStream out2 = new FileOutputStream(dist);
BufferedInputStream bis = new BufferedInputStream(in2);
BufferedOutputStream bos = new BufferedOutputStream(out2);
byte[] buffer2 = new byte[20 * 1024];
int cnt2;
while ((cnt2 = bis.read(buffer2)) != -1) {
bos.write(buffer2, 0 , cnt2);
}
in2.close();
out2.close();
bis.close();
bos.close();
long end3 = System.currentTimeMillis();
System.out.println("缓存类时用的时间:" + (end3 - start3));
}
生成个文件
public static void test() throws IOException {
File file = new File("d:/a.txt");
FileOutputStream fos = new FileOutputStream(file);
fos.write('g');
fos.write('z');
fos.write("五星上酱".getBytes());
fos.close();
System.out.println("已完成");
}
原文件上增加数据
public static void test2() throws IOException {
OutputStream os = new FileOutputStream(new File("d:/b.txt"));
os.write("-----原数据----".getBytes());
os.close();
OutputStream os2 = new FileOutputStream("d:/b.txt", true);
os2.write("\r\n".getBytes());
os2.write("---insert---".getBytes());
os2.close();
}
FileReader读取txt文档
提前准备好d:/b.txt
public static void test21() throws IOException{
FileReader fis = null;
try {
fis = new FileReader("d:/b.txt");
char[] c = new char[1024];
int hasRead;
while ((hasRead = fis.read(c)) != -1) {
System.out.println(new String(c, 0, hasRead));
}
} catch (Exception e) {
e.printStackTrace();
} finally {
fis.close();
}
}
转换流InputStreamReader,解决乱码问题
/**
* win10新建的txt默认是gbk,但是idea中默认是utf-8
* 提前在电脑手动新建d:/b.txt,输入中文
* @throws IOException
*/
public static void test7() throws IOException {
//默认是utf-8,所以输出乱码
InputStreamReader reader = new InputStreamReader(new FileInputStream("d:/b.txt"));
int len;
while ((len = reader.read()) != -1) {
System.out.println((char)len);
}
reader.close();
//不乱码
InputStreamReader reader2 = new InputStreamReader(new FileInputStream("D:/b.txt"), "gbk");
int len2;
while((len2 = reader2.read()) != -1) {
System.out.println((char)len2);
}
reader2.close();
}
图片用BASE64Encoder编码,BASE64Decoder解码
public static void test8() throws IOException {
FileInputStream fis = new FileInputStream("C:/Users/Lenovo/Desktop/design.jpg");
StringBuilder sb = new StringBuilder();
byte[] b = new byte[1024];
int hasRead = 0;
BASE64Encoder base64Encoder = new BASE64Encoder();
while ((hasRead = fis.read(b)) != -1) {
sb.append(base64Encoder.encode(b));
}
System.out.println("BASE64Encoder编码:" + sb.toString());
BASE64Decoder base64Decoder = new BASE64Decoder();
byte[] bd = base64Decoder.decodeBuffer(sb.toString());
File file = new File("C:/Users/Lenovo/Desktop/design2.jpg");
FileOutputStream fos = new FileOutputStream(file);
BufferedOutputStream bos = new BufferedOutputStream(fos);
bos.write(bd);
fis.close();
fos.close();
}
对象操作
把对象A序列化保存,然后再读取为对象
public static void main(String[] args) throws IOException, ClassNotFoundException {
A a1 = new A(123, "abc", "小明");
String objectFile = "d:/a1";
ObjectOutputStream objectOutputStream = new ObjectOutputStream(new FileOutputStream(objectFile));
objectOutputStream.writeObject(a1);
objectOutputStream.close();
ObjectInputStream objectInputStream = new ObjectInputStream(new FileInputStream(objectFile));
A a2 = (A) objectInputStream.readObject();
objectInputStream.close();
//不会打印c小明
System.out.println(a2);
}
}
class A implements Serializable {
private int x;
private String y;
//transient 关键字可以使一些属性不会被序列化。
private transient String c;
A(int x, String y, String c) {
this.x = x;
this.y = y;
this.c = c;
}
@Override
public String toString() {
return "A{" +
"x=" + x +
", y='" + y + '\'' +
", c='" + c + '\'' +
'}';
}
}
URL读取操作
public static void main(String[] args) throws IOException, ClassNotFoundException {
URL url = new URL("http://www.baidu.com");
InputStream is = url.openStream();
InputStreamReader isr = new InputStreamReader(is, "utf-8");
BufferedReader br = new BufferedReader(isr);
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
is.close();
isr.close();
br.close();
}
URLConnection获得IO信息
public static void URLCon() throws IOException {
InputStream inputStream = null;
FileOutputStream ops = null;
try {
URL url = new URL("http://www.baidu.com");
URLConnection conn = url.openConnection();
inputStream = conn.getInputStream();
ops = new FileOutputStream("C:/Users/Lenovo/Desktop/baidu.html");
byte[] buffer = new byte[1024];
int bytestRead;
while ((bytestRead = inputStream.read(buffer)) != -1) {
ops.write(buffer, 0, bytestRead);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
inputStream.close();
ops.close();
}
}
使用 NIO 快速复制文件的实例
public static void fastCopy(String src, String dist) throws IOException {
/* 获得源文件的输入字节流 */
FileInputStream fin = new FileInputStream(src);
/* 获取输入字节流的文件通道 */
FileChannel fcin = fin.getChannel();
/* 获取目标文件的输出字节流 */
FileOutputStream fout = new FileOutputStream(dist);
/* 获取输出字节流的文件通道 */
FileChannel fcout = fout.getChannel();
/* 为缓冲区分配 1024 个字节 */
ByteBuffer buffer = ByteBuffer.allocateDirect(1024);
while (true) {
/* 从输入通道中读取数据到缓冲区中 */
int r = fcin.read(buffer);
/* read() 返回 -1 表示 EOF */
if (r == -1) {
break;
}
/* 切换读写 */
buffer.flip();
/* 把缓冲区的内容写入输出文件中 */
fcout.write(buffer);
/* 清空缓冲区 */
buffer.clear();
}
fin.close();
fcin.close();
fout.close();
fcout.close();
}
socket应用NIO实例
//服务端
public class NIOServer {
public static void main(String[] args) throws IOException {
Selector selector = Selector.open();
ServerSocketChannel ssChannel = ServerSocketChannel.open();
ssChannel.configureBlocking(false);
ssChannel.register(selector, SelectionKey.OP_ACCEPT);
ServerSocket serverSocket = ssChannel.socket();
InetSocketAddress address = new InetSocketAddress("127.0.0.1", 8888);
serverSocket.bind(address);
while (true) {
selector.select();
Set<SelectionKey> keys = selector.selectedKeys();
Iterator<SelectionKey> keyIterator = keys.iterator();
while (keyIterator.hasNext()) {
SelectionKey key = keyIterator.next();
if (key.isAcceptable()) {
ServerSocketChannel ssChannel1 = (ServerSocketChannel) key.channel();
// 服务器会为每个新连接创建一个 SocketChannel
SocketChannel sChannel = ssChannel1.accept();
sChannel.configureBlocking(false);
// 这个新连接主要用于从客户端读取数据
sChannel.register(selector, SelectionKey.OP_READ);
} else if (key.isReadable()) {
SocketChannel sChannel = (SocketChannel) key.channel();
System.out.println(readDataFromSocketChannel(sChannel));
sChannel.close();
}
keyIterator.remove();
}
}
}
private static String readDataFromSocketChannel(SocketChannel sChannel) throws IOException {
ByteBuffer buffer = ByteBuffer.allocate(1024);
StringBuilder data = new StringBuilder();
while (true) {
buffer.clear();
int n = sChannel.read(buffer);
if (n == -1) {
break;
}
buffer.flip();
int limit = buffer.limit();
char[] dst = new char[limit];
for (int i = 0; i < limit; i++) {
dst[i] = (char) buffer.get(i);
}
data.append(dst);
buffer.clear();
}
return data.toString();
}
}
//客户端
public class NIOClient {
public static void main(String[] args) throws IOException {
Socket socket = new Socket("127.0.0.1", 8888);
OutputStream out = socket.getOutputStream();
String s = "hello world";
out.write(s.getBytes());
out.close();
}
}