IO作用:解決設(shè)備和設(shè)備之間數(shù)據(jù)傳輸問題,內(nèi)存->硬盤,硬盤->內(nèi)存,鍵盤數(shù)據(jù)->內(nèi)存數(shù)據(jù)存到硬盤上,就做到了永久保存,數(shù)據(jù)一般是以文件形式保存到硬盤上,sun用File描述文件文件夾
File構(gòu)造方法
File file = new File(String pathname);
public class Test {
public static void main(String[] args) {
File file = new File("E:\\test.txt");
try {
file.createNewFile();
}catch (Exception e){
e.printStackTrace();
}
}
}
在文件夾里創(chuàng)建文件
File file = new File (String 文件夾, String 文件名);
public class Test {
public static void main(String[] args) {
File file = new File("E:\\k","test.txt");
try {
file.createNewFile();
}catch (Exception e){
e.printStackTrace();
}
}
}
在文件夾中的文件夾里創(chuàng)建文件
public class Test {
public static void main(String[] args) {
File file1 = new File("E:\\k\\k")
File file = new File(file1,"test.txt");
try {
file.createNewFile();
}catch (Exception e){
e.printStackTrace();
}
}
}
絕對(duì)路徑 & 相對(duì)路徑
相對(duì)路徑不能跨盤
相對(duì)路徑:../../Test1.txt, ./Test1.txt = Test1.txt
創(chuàng)建
創(chuàng)建文件:
createNewFile();
創(chuàng)建單層文件夾:
mkdir();
//在E盤里創(chuàng)建一個(gè)叫k的文件夾
File file = new File("E:/k");
try{
file.mkdir();
}catch(Exception e){
e.printStackTrace();
}
mkdir
public boolean mkdir()
創(chuàng)建此抽象路徑名指定的目錄。
返回:
當(dāng)且僅當(dāng)已創(chuàng)建目錄時(shí),返回 true;否則返回 false
File file = new File("E:.k.txt");
boolean b = file.mkdir();
System.out.println(b);
創(chuàng)建多層文件夾:
mkdirs();
File file = new File("E:/a/b/c/d");
file.mkdirs();
文件重命名:
File srcFile = new File("E:/test.txt");
File destFile = new File("E:/k.txt");
srcFile.renameTo(destFile);
刪除文件(夾):
File srcFile = new File("E:/test.txt");
File destFile = new File("E:/k.txt");
srcFile.delete();
刪除成功返回true,否則返回false
存在:
exists();
System.out.println(srcFile.exists());
boolean型, 存在返回true,否則返回false
是不是文件: src.isFile(); boolean型
是不是目錄:isDirectory(); boolean
是不是一個(gè)目錄: isDirectory(); boolean
是否被隱藏: isHidden(); boolean
是否是絕對(duì)路徑: isAbsolute(); boolean
獲取文件名: getName(); String
獲取(假)絕對(duì)路徑: getPath(); String
獲取絕對(duì)路徑: getAbsolutePath(); String
獲取文件內(nèi)容字節(jié)個(gè)數(shù): long length();
獲取最后一次修改時(shí)間: lastModified();
獲取次抽象路徑名表示的目錄中的所有子文件(夾):
File[] listFiles(); 數(shù)組
File file = new File("E:/k");
File[] list = file.listFiles();
for(File file1 : list){
System.out.println(file1.getName());
}
//或取E盤k文件夾下的文件(夾)名
public class Test {
public static void main(String[] args) {
File file = new File("E:/k");
test(file);
}
public static void test(File file){
File[] files = file.listFiles();
for (int i = 0; i < files.length; i++){
if (files[i].isFile()){
System.out.println(files[i].getName());
}else {
test(files[i]);
}
}
}
}
//獲取E盤k文件夾里所有文件名
獲取文件夾里的所有文件:
遞歸思想
public class Practice {
public static void main(String[] args) {
PrintFiles("e/neusoft");
}
public static void PrintFiles(String path){
File file1 = new File(path);
File[] files = file1.listFiles();
for (File file : files){
if (file.isFile()) {
System.out.println(file.getName());
}
else if (file.isDirectory()){
System.out.println(file.getAbsolutePath());
PrintFiles(file.getAbsolutePath());
}
}
}
}
流
流是指一連串流動(dòng)的字符,是以先進(jìn)先出方式發(fā)送信息的通道。
通過流來讀寫文件。
字符,字節(jié)流:
- 往文本文檔里寫東西是字符流,字符輸入流Reader,字符輸出流Writer
- 往word里寫東西是字節(jié)流,字節(jié)輸入流InputStream,字符輸出流OutputStream
輸入,輸出流: - 往內(nèi)存里讀叫輸入流,InputStream 和Reader作為基類
- 從內(nèi)存出叫輸出流,OutputStream和Writer作為基類
文本文件的讀寫:
- 用FileInputStream和FileOutputStream讀寫
- 用BufferedReader和BufferedWriter讀寫
二進(jìn)制文件讀寫:
- 使用DataInputStream和DataOutputStream讀寫
使用FileInputStream讀寫:
InputStream類常用方法:
int read( ) 讀取一個(gè)字節(jié)
int read(byte[] b) 讀取一批字節(jié)
int read(byte[] b,int off,int len)
void close( )
子類FileInputStream常用的構(gòu)造方法
FileInputStream(File file)
FileInputStream(String name)
byte[] buffer = new byte[10];
buffer[0] = 97;
buffer[1]=98;//b
String string = new String(buffer,0//offset,2//length);
System.out.println(string);
read()
File file = new File("e:/test.txt");
System.out.println(file.length());
byte[] buffer = new byte[(int)file.length()];
FileInputStream fileInputStream = new FileInputStream(file);
int index = 0;
byte content = (byte)fileInputStream.read();//讀取文件的一個(gè)字節(jié)
while (content != -1){
buffer[index] = content;
index++;
content = (byte)fileInputStream.read();
}
System.out.println(Arrays.toString(buffer));
String string = new String(buffer,0,index);
System.out.println(string);
read(byte[] b)
public static void main(String[] args) throws IOException {
// write your code here
File file = new File("d:/我的青春誰做主.txt");
FileInputStream fileInputStream = new FileInputStream(file);
byte[] buffer = new byte[SIZE];//保存從磁盤讀到的字節(jié)
int len = fileInputStream.read(buffer);//第一次讀文件中的100個(gè)字節(jié)
while (len != -1)
{
String string = new String(buffer,0, len);
System.out.println(string);
//讀下一批字節(jié)
len = fileInputStream.read(buffer);
}
}
寫文件:
FileOutputStream fileOutputStream = new FileOutputStream("e:/test.txt");
String string = "good job";
byte[] words = string.getBytes();
fileOutputStream.write(words,0,words.length);
OutputStream類常用方法
void write(int c)
void write(byte[] buf)
void write(byte[] b,int off,int len)
void close( )
子類FileOutputStream常用的構(gòu)造方法
FileOutputStream (File file)
FileOutputStream(String name)
FileOutputStream(String name,boolean append)
1、前兩種構(gòu)造方法在向文件寫數(shù)據(jù)時(shí)將覆蓋文件中原有的內(nèi)容
2、創(chuàng)建FileOutputStream實(shí)例時(shí),如果相應(yīng)的文件并不存在,則會(huì)自動(dòng)創(chuàng)建一個(gè)空的文件
復(fù)制文件內(nèi)容
文件“我的青春誰做主.txt”位于D盤根目錄下,要求將此文件的內(nèi)容復(fù)制到
C:\myFile\my Prime.txt中
實(shí)現(xiàn)思路:
創(chuàng)建文件“D:\我的青春誰做主.txt”并自行輸入內(nèi)容
創(chuàng)建C:\myFile的目錄。
創(chuàng)建輸入流FileInputStream對(duì)象,負(fù)責(zé)對(duì)D:\我的青春誰做主.txt文件的讀取。
創(chuàng)建輸出流FileOutputStream對(duì)象,負(fù)責(zé)將文件內(nèi)容寫入到C:\myFile\my Prime.txt中。
創(chuàng)建中轉(zhuǎn)站數(shù)組words,存放每次讀取的內(nèi)容。
通過循環(huán)實(shí)現(xiàn)文件讀寫。
關(guān)閉輸入流、輸出流
File file = new File("e:/Test.txt");
File file1 = new File("d:/myFile");
try{
file1.mkdir();
}catch (Exception e){
e.printStackTrace();
}
File file2 = new File("d:/myFile/my Prime.txt");
FileInputStream fileInputStream = new FileInputStream(file);
FileOutputStream fileOutputStream = new FileOutputStream(file2);
byte[] buffer = new byte[5];
int read_len = fileInputStream.read(buffer);
while (read_len != -1){
String string = new String(buffer,0,read_len);
System.out.println(string);
byte[] words = string.getBytes();
fileOutputStream.write(words,0,words.length);
read_len = fileInputStream.read(buffer);
}
File file = new File("e:/c2fdfc039245d688c56332adacc27d1ed21b2451.jpg");
File file1 = new File("d:/myFile");
if (!file1.exists()){
file1.mkdir();
}
File file2 = new File("d:/myFile/my Prime.jpg");
FileInputStream fileInputStream = new FileInputStream(file);
FileOutputStream fileOutputStream = new FileOutputStream(file2);
byte[] buffer = new byte[10];
int read_len = fileInputStream.read(buffer);
while (read_len != -1){
fileOutputStream.write(buffer,0,buffer.length);
read_len = fileInputStream.read(buffer);
}
fileInputStream.close();
fileOutputStream.close();
使用字符流讀寫文件
使用FileReader讀取文件
public static void main(String[] args) throws IOException {
//
FileReader fileReader = new FileReader("D:/我的青春誰做主.txt");
char[] array = new char[100];
int length = fileReader.read(array);
StringBuilder sb = new StringBuilder();//拼接字符串
while (length != -1)
{
sb.append(array);//追加字符串
length = fileReader.read(array);
}
System.out.println(sb.toString());
fileReader.close();
}
FileReader fileReader = new FileReader("e:/test.txt");
char[] chars = new char[5];
int length = fileReader.read(chars);
StringBuilder stringBuilder = new StringBuilder();
int count = 0;
while (length != -1){
count++;
System.out.println(count);
stringBuilder.append(chars);
Arrays.fill(chars,'\u0000');
length = fileReader.read(chars);
}
System.out.println(stringBuilder.toString());
fileReader.close();
BufferedReader類
使用FileReader類與BufferedReader類
BufferedReader類是Reader類的子類
BufferedReader類帶有緩沖區(qū)
按行讀取內(nèi)容的readLine()方法
public static void main(String[] args) throws IOException {
FileReader fileReader = new FileReader("D:/我的青春誰做主.txt");
BufferedReader bufferedReader = new BufferedReader(fileReader);
String strContent = bufferedReader.readLine();
StringBuilder sb = new StringBuilder();
while (strContent != null)
{
sb.append(strContent);
sb.append("\n");
sb.append("\r");
strContent = bufferedReader.readLine();
}
System.out.println(sb.toString());
fileReader.close();
bufferedReader.close();
}
使用FileWriter寫文件
FileWriter fileWriter = new FileWriter("e:/test.txt");
fileWriter.append("hello world");
fileWriter.flush();
fileWriter.close();
如何提高字符流寫文本文件的效率?
使用FileWriter類與BufferedWriter類
BufferedWriter類是Writer類的子類
BufferedWriter類帶有緩沖區(qū)
image.png
public class BufferedWriterTest {
public static void main(String[] args) {
FileWriter fw=null;
BufferedWriter bw=null;
FileReader fr=null;
BufferedReader br=null;
try {
//創(chuàng)建一個(gè)FileWriter 對(duì)象
fw=new FileWriter("D:\\myDoc\\hello.txt");
//創(chuàng)建一個(gè)BufferedWriter 對(duì)象
bw=new BufferedWriter(fw);
bw.write("大家好!");
bw.write("我正在學(xué)習(xí)BufferedWriter。");
bw.newLine();
bw.write("請(qǐng)多多指教!");
bw.newLine();
bw.flush();
//讀取文件內(nèi)容
fr=new FileReader("D:\\myDoc\\hello.txt");
br=new BufferedReader(fr);
String line=br.readLine();
while(line!=null){
System.out.println(line);
line=br.readLine();
}
fr.close();
}catch(IOException e){
System.out.println("文件不存在!");
}finally{
try{
if(fw!=null)
fw.close();
if(br!=null)
br.close();
if(fr!=null)
fr.close();
}catch(IOException ex){
ex.printStackTrace();
}
}
}
}
文本拷貝
FileReader fr = new FileReader("e:/test.txt");
FileWriter wr = new FileWriter("d:/myFile/my Prime.txt");
BufferedReader reader = new BufferedReader(fr);
BufferedWriter writer = new BufferedWriter(wr);
StringBuffer str = new StringBuffer();
String line = reader.readLine();
while (line != null){
str.append(line);
str.append("\n");
str.append("\t");
wr.flush();
line = reader.readLine();
}
System.out.println(str.toString());
String string = str.toString().replace("{name}","golden");
string = string.toString().replace("{type}","dog");
string = string.toString().replace("{master}","zabrath");
System.out.println(string);
writer.write(string);
writer.flush();
練習(xí) 統(tǒng)計(jì)某個(gè)文件夾下所有java文件代碼行數(shù)之和:
File file = new File("C:\\Users\\Administrator\\IdeaProjects\\jemalsjava\\src\\com\\company\\");
File[] arr = file.listFiles();
int totalCount = 0;
for (File file1 : arr){
FileReader fileReader = new FileReader(file1);
BufferedReader bufferedReader = new BufferedReader(fileReader);
int countLine = 0;
String strLine = bufferedReader.readLine();
while (strLine != null){
countLine++;
strLine = bufferedReader.readLine();
}
totalCount += countLine;
}
System.out.println(totalCount);
package com.company;
import java.io.*;
/**
* Created by ttc on 2018/6/5.
*/
public class CodeLinesCount {
public static int CountLines(String filename) throws IOException {
FileReader fileReader = new FileReader(filename);
BufferedReader bufferedReader = new BufferedReader(fileReader);
int count = 0;
String strLine = bufferedReader.readLine();
while(strLine != null)
{
count++;
strLine = bufferedReader.readLine();
}
System.out.println(count);
return count;
}
public static void main(String[] args) throws IOException {
// CountLines("d:/Main.java");
File file = new File("D:\\javacode");
File[] files = file.listFiles();
int sum = 0;
for(File file1 : files)
{
System.out.println(file1.getPath());
int count = CountLines(file1.getPath());
sum += count;
}
System.out.println(sum);
}
}
DataOutputStream和DataInputStream
DataOutputStream數(shù)據(jù)輸出流: 將java基本數(shù)據(jù)類型寫入數(shù)據(jù)輸出流中。
DataInputStream數(shù)據(jù)輸入流:將DataOutputStream寫入流中的數(shù)據(jù)讀入。
DataOutputStream中write的方法重載:
繼承了字節(jié)流父類的兩個(gè)方法:
(1)void write(byte[] b,int off,int len);
(2)void write(int b);//寫入U(xiǎn)TF數(shù)值,代表字符
注意字節(jié)流基類不能直接寫入string 需要先將String轉(zhuǎn)化為getByte()轉(zhuǎn)化為byte數(shù)組寫入
特有的指定基本數(shù)據(jù)類型寫入:
(1)void writeBoolean(boolean b);//將一個(gè)boolean值以1byte形式寫入基本輸出流。
(2)void writeByte(int v);//將一個(gè)byte值以1byte值形式寫入到基本輸出流中。
(3)void writeBytes(String s);//將字符串按字節(jié)順序?qū)懭氲交据敵隽髦小?br>
(4)void writeChar(int v);//將一個(gè)char值以2byte形式寫入到基本輸出流中。先寫入高字節(jié)。寫入的也是編碼值;
(5)void writeInt(int v);//將一個(gè)int值以4byte值形式寫入到輸出流中先寫高字節(jié)。
(6)void writeUTF(String str);//以機(jī)器無關(guān)的的方式用UTF-8修改版將一個(gè)字符串寫到基本輸出流。該方法先用writeShort寫入兩個(gè)字節(jié)表示后面的字節(jié)數(shù)。
DataInputStream中read方法重載:
繼承了字節(jié)流父類的方法:
int read();
int read(byte[] b);
int read(byte[] buf,int off,int len);
對(duì)應(yīng)write方法的基本數(shù)據(jù)類型的讀出:
String readUTF();//讀入一個(gè)已使用UTF-8修改版格式編碼的字符串
boolean readBoolean;
int readInt();
byte readByte();
char readChar();
注意:
基本數(shù)據(jù)類型的寫入流和輸出流,必須保證以什么順序按什么方式寫入數(shù)據(jù),就要按什么順序什么方法讀出數(shù)據(jù),否則會(huì)導(dǎo)致亂碼,或者異常產(chǎn)生。
public class DataStream {
public static void main(String[] args) throws IOException {
String[] strings = {"main","flush","String","FileOutputStream","java.io.*"};
FileOutputStream fileOutputStream = new FileOutputStream("e:/output.txt");
DataOutputStream dataOutputStream = new DataOutputStream(fileOutputStream);
for(String string : strings)
{
int strlen = string.length();
dataOutputStream.writeShort(strlen);
dataOutputStream.writeBytes(string);
}
dataOutputStream.flush();
dataOutputStream.close();
FileInputStream fileInputStream = new FileInputStream("e:/output.txt");
DataInputStream dataInputStream = new DataInputStream(fileInputStream);
while(true)
{
try {
short len = dataInputStream.readShort();
byte[] bytes = new byte[len];
dataInputStream.read(bytes);
String string = new String(bytes,0,bytes.length);
System.out.println(string);
}
catch (EOFException ex)
{
break;
}
}
}
}