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

Java基础 4000 之基本IO操作

2017-07-11 21:18 459 查看
文章的内容参考了 http://blog.csdn.net/yczz/article/details/38761237,对博主表示感谢。
java的IO体系包括字符流和字节流,如下图所示:



下面对常见的IO操作举例,如果想要参考IO的其他流操纵,请阅读官方的API文档

import java.io.*;

import static java.lang.System.*;

/**
* Created by leo on 17-7-11.
*/
public class IONote {
public static void main(String[] args){
IONote note = new IONote();

// note.createFile("/home/leo/Java/io.txt");
// note.copyFile();
// note.countLines();
note.useBufferWriter();
}

public void createFile(String fileName){
File file = new File(fileName);
try {
file.createNewFile();
// out.println(file.getTotalSpace()/1024/1024/1024 + "G");
file.mkdirs();
out.println(file.getName());
out.println(file.getParent());
} catch (IOException e) {
e.printStackTrace();
}
}

// copy file
public void copyFile(){
byte[] buffer = new byte[1024];
FileInputStream inputStream = null;
FileOutputStream outputStream = null;

try {
inputStream = new FileInputStream("/home/leo/Java/io.txt");
outputStream = new FileOutputStream("/home/leo/Java/io.txt.copy1");
int numberRead = inputStream.read(buffer);
while (numberRead != -1){
outputStream.write(buffer, 0, numberRead);
numberRead = inputStream.read();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
inputStream.close();
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}

// BufferReader,FileInputStream
public void countLines(){
BufferedReader reader = null;
try {
reader = new BufferedReader(new InputStreamReader(new FileInputStream("/home/leo/Java/io.txt.copy")));
int charCounts = 0;
Long lineCounts = 0L;
// while (reader.read() != -1){
// charCounts += 1;
// }
// 无论是读一个字符还是一行,每read或者readLine一次,读的指针就往前一步
while (reader.readLine() != null){
out.println(reader.readLine());
lineCounts += 1;
}
out.println("charCounts=" + charCounts + " " + "lineCounts=" + lineCounts);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}

// BufferWriter
public void useBufferWriter(){
try {
FileWriter fileWriter = new FileWriter("/home/leo/Java/io.txt.copy1");
BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
bufferedWriter.write("hello");
bufferedWriter.newLine(); //写入一个换行符
bufferedWriter.write("world");
bufferedWriter.flush();
bufferedWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  字符流 java io