您的位置:首页 > 编程语言 > Java开发

java IO练习

2016-06-23 23:53 405 查看
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.io.RandomAccessFile;
import java.io.SequenceInputStream;
import java.nio.file.Path;

import org.junit.Test;

/*
* @author AloneBo
* */
public class TestIO  {

private static String PATH = "G:";

//File基本方法
@Test
public void test1() throws IOException {
File file = new File("G:\\hello.txt");
if (!file.exists()) {
file.createNewFile();
System.out.println("OK!");
}else{
System.out.println("文件已经存在");
}
}

//分隔符
@Test
public void test2() {
System.out.println(File.pathSeparator);
System.out.println(File.separator);
}

//基本方法
@Test
public void test3() throws IOException {
File file = new File(PATH+File.separator+"hello.txt");
if (file.exists()) {
System.out.println("file exit!");

}else {
file.createNewFile();
System.out.println("文件创建成功");
}
}

//基本方法
@Test
public void test4() {
String filePath = PATH+File.separator+"hello.txt";
File file = new File(filePath);
if (file.exists()) {
file.delete();
System.out.println("文件删除成功");
}else{
System.out.println("文件不存在");

}
}

//mkdir与midirs
@Test
public void test5(){
String dirPath = PATH+File.separator+"hello"+File.separator+"haha";
File file = new File(dirPath);
if (file.exists()) {
System.out.println("文件存在");
}else{
file.mkdirs();//与mkdir有所区别

}
}

//输出文件名
@Test
public void test6() {
String filePath = PATH+File.separator;
File file = new File(filePath);
String[] list = file.list();
for (int i = 0; i < list.length; i++) {
System.out.println(list[i]);
}
}

//输出全路径
@Test
public void test7() {
String filePath = PATH+File.separator+"code"+File.separator+"java";
File file = new File(filePath);
File[] listFiles = file.listFiles();
for (int i = 0; i < listFiles.length; i++) {
System.out.println(listFiles[i]);
}
}

//基本方法
@Test
public void test8() {
String filePath = PATH+File.separator+"code";
File file = new File(filePath);
if (file.isDirectory()) {
System.out.println("File is a directory");
}else{
System.out.println("File not is a directory");
}
}

//输出制定目录所有文件
@Test
public void test9() {
String filePath = PATH+File.separator+"书籍";
File file = new File(filePath);
printAll(file);
}

private void printAll(File file) {
if (file!=null) {
if (file.isDirectory()) {
File[] listFiles = file.listFiles();
for (int i = 0; i < listFiles.length; i++) {
printAll(listFiles[i]);//递归
}
}
else {
System.out.println(file);
}
}
}

//随机访问
@Test
public void test10() throws IOException {
String filePath = PATH+File.separator+"hello.txt";
File file = new File(filePath);
RandomAccessFile randomAccessFile = new RandomAccessFile(file, "rw");
randomAccessFile.writeInt(12);
randomAccessFile.writeBytes("haaa");
randomAccessFile.writeBoolean(false);
randomAccessFile.writeChar('s');
randomAccessFile.writeFloat(1.23f);
randomAccessFile.writeDouble(12.344);
randomAccessFile.close();
}

//FileOutputStream测试
@Test
public void test11() throws IOException {
String filePath = PATH+File.separator+"hello.txt";
File file = new File(filePath);
FileOutputStream fileOutputStream = new FileOutputStream(file);
String string = "你好";
byte[] bs = string.getBytes();
fileOutputStream.write(bs);
fileOutputStream.flush();
fileOutputStream.close();
}

//FileOutputStream测试
@Test
public void test12() throws IOException {
String filePath = PATH+File.separator+"hello.txt";
OutputStream outputStream = new FileOutputStream(new File(filePath),true);
String string = "\nhaha";
byte[] bs = string.getBytes();
outputStream.write(bs);
outputStream.flush();
outputStream.close();
}

//FileInputStream测试,当文件大于byte[size]时错误
@Test
public void test13() throws IOException {
String filePath = new String(PATH+File.separator+"hello.txt");
FileInputStream fileInputStream = new FileInputStream(filePath);
byte[] bs = new byte[1024];
int length = fileInputStream.read(bs);
System.out.println(new String(bs,0,length));//error!!!!
fileInputStream.close();
}

//FileInputStream测试
@Test
public void test14() throws IOException {
String filePath = PATH+File.separator+"hello.txt";
File file = new File(filePath);
FileInputStream fileInputStream = new FileInputStream(file);
byte[] bs = new byte[(int) file.length()];
fileInputStream.read(bs);
fileInputStream.close();
System.out.println(new String(bs));

}

//输出文件内容字节流
@Test
public void test15() throws IOException {
String filePath = PATH+File.separator+"hello.txt";
File file = new File(filePath);
FileInputStream fileInputStream = new FileInputStream(file);

//      int c = -1;
//      StringBuffer stringBuffer = new StringBuffer();
//      while((c=fileInputStream.read()) != -1) {
//          char ch = (char)c;
//          stringBuffer.append(ch);
//      }
//      System.out.println(stringBuffer.toString());//乱码!效率低下

StringBuffer stringBuffer = new StringBuffer();
byte[] b = new byte[1024];
int count = -1;
while((count=fileInputStream.read(b)) != -1) {
stringBuffer.append(new String(b, 0, count,"UTF-8"));
}
System.out.println(stringBuffer.toString());//文件不会乱码
fileInputStream.close();

}

//字符流
@Test
public void test16() throws IOException {
String filePath = PATH+File.separator+"hello.txt";
File file = new File(filePath);
FileWriter fileWriter = new FileWriter(file,true);
fileWriter.write("中文字符");
fileWriter.flush();
fileWriter.close();
System.out.println("写入成功");
}

//输出文件内容,字符流
@Test
public void test18() throws IOException {
String filePath = PATH+File.separator+"hello.txt";
File file = new File(filePath);
FileReader fileReader = new FileReader(file);
char[] cbuf = new char[1024];
int count = -1;
int size = 0;
StringBuffer stringBuffer = new StringBuffer();
while((count = fileReader.read(cbuf)) != -1) {
stringBuffer.append(new String(cbuf,0,count));
size++;
}
System.out.println(stringBuffer.toString());
System.out.println("文本大小大概为"+size+"k");
fileReader.close();
}

//文件的复制
@Test
public void test19() throws IOException {
String filePath = PATH+File.separator+"1.zip";
String copyPath = PATH+File.separator+"3.zip";
File file = new File(filePath);
File copyFile = new File(copyPath);
InputStream inputStream = new FileInputStream(file);
OutputStream outputStream = new FileOutputStream(copyFile);
byte[] b = new byte[1024];
int count = 0;
long time1 = System.currentTimeMillis();
//System.out.println(time1);
while((count = inputStream.read(b)) != -1) {
outputStream.write(b,0,count);
}
long time2 = System.currentTimeMillis();
//System.out.println(time2);
long usetime = (time2-time1)/1000;
System.out.println("复制成功,用时:"+usetime+"s");
long length = file.length()/(1024*1024);
System.out.println("文件大小"+length+"M");
System.out.println("平均速度"+length/usetime+"M/s");
outputStream.flush();
outputStream.close();
inputStream.close();
}

//转换流
@Test
public void fun20() throws IOException {
String filePath = PATH+File.separator+"hello.txt";
File file = new File(filePath);
//建议用Buffer包裹
BufferedReader bufferedReader = new BufferedReader(new FileReader(file));//没用转换了...
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(new File(filePath),true)));//加上true,否则都会清空,在这行执行后
StringBuffer stringBuffer = new StringBuffer();
String str="";
while((str  = bufferedReader.readLine()) != null) {
stringBuffer.append(str+"\n");//默认是没有换行符的
//System.out.println(str);//也可以这样输出
}
System.out.println(stringBuffer);
bufferedReader.close();
bufferedWriter.close();
}

//打印流
@Test
public void fun21() throws IOException {

bbe5
String filePath = PATH+File.separator+"hello.txt";
File file = new File(filePath);
PrintStream printStream = new PrintStream(file);
printStream.println("hello----------------------------------------------------------hello");//会清空
printStream.flush();
printStream.close();

//------------------------------------------------------------------------------------------
PrintWriter printWriter = new PrintWriter(new FileOutputStream(file,true),true);//true为append 和 autoflush
printWriter.print("hahaha--------------------------------------------------------------hahha");
printWriter.flush();
printWriter.close();
}

//从控制台不断读取写到文件中,直到输入exit
@Test
public void fun22() throws IOException {
String filePath = PATH+File.separator+"hello.txt";
File file = new File(filePath);
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file,true)));
String string = "";
do {
string = bufferedReader.readLine();
bufferedWriter.write(string+"\n");
} while (!string.equals("exit"));// do while先执行循环,然后在判断循环条件

bufferedWriter.flush();
bufferedReader.close();
bufferedWriter.close();
}

//合并流
@Test
public void fun23() throws IOException {
String fileName1= PATH+File.separator+"A.txt";//先试试txt
String fileName2 = PATH+File.separator+"B.txt";
String fileName3 = PATH+File.separator+"AB.txt";

PrintStream printStream = new PrintStream(new File(fileName1));
printStream.println("abcd");
PrintStream printStream2 = new PrintStream(new File(fileName2));
printStream2.println("efgh");
printStream.flush();
printStream2.flush();
printStream.close();
printStream2.close();

SequenceInputStream sequenceInputStream = new SequenceInputStream(new FileInputStream(new File(fileName1)), new FileInputStream(new File(fileName2)));
OutputStream outputStream = new FileOutputStream(new File(fileName3));

byte[] bs = new byte[1024];
int i=0;
while((i=sequenceInputStream.read(bs)) != -1) {
outputStream.write(bs, 0, i);
}

sequenceInputStream.close();
outputStream.flush();
outputStream.close();

}

//加密文件
@Test
public void fun24() throws IOException {
String fileName = PATH+File.separator+"password.txt";
String fileName2 = PATH+File.separator+"password.ede";
FileInputStream fileInputStream = new FileInputStream(new File(fileName));
FileOutputStream fileOutputStream = new FileOutputStream(new File(fileName2));
int count = 0;
while ((count = fileInputStream.read()) != -1) {
count++;
fileOutputStream.write(count);
}

fileInputStream.close();
fileOutputStream.close();
}

//解密文件
@Test
public void fun25() throws IOException {
String fileName = PATH+File.separator+"password.ede";
String fileName2 = PATH+File.separator+"password2.txt";
FileInputStream fileInputStream = new FileInputStream(new File(fileName));
FileOutputStream fileOutputStream = new FileOutputStream(new File(fileName2));
int count = 0;
while ((count = fileInputStream.read()) != -1) {
count--;
fileOutputStream.write(count);
}

fileInputStream.close();
fileOutputStream.close();
}

//对象序列化,将对象转换成二进制流,实现对象传输与保存.
@Test
public void fun26() throws IOException, ClassNotFoundException {
TestIO testIO = new TestIO();
Person person = new Person("jerry", 18);
String fileName = PATH+File.separator+"SerializePerson.object";
File file = new File(fileName);
serialize(file,person);
Person getPersion = (Person) deSerialize(file);
System.out.println(getPersion.name);
}
private void serialize(File file,Object object) throws IOException {
OutputStream outputStream = new FileOutputStream(file);
ObjectOutputStream objectOutputStream = new ObjectOutputStream(outputStream);
objectOutputStream.writeObject(object);
objectOutputStream.close();
}
private Object deSerialize(File file) throws IOException, ClassNotFoundException {
InputStream inputStream = new FileInputStream(file);
ObjectInputStream objectInputStream = new ObjectInputStream(inputStream);
Object object = objectInputStream.readObject();
objectInputStream.close();
return object;
}

@Test
public void fun27() {
System.out.println("Hello World");
}

}


如有错误之处或建议欢迎指出

There is a way, there is a will
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: