Java(IO入出力)——txtファイルの読み取り、書き込み、コピー
1699 ワード
import java.io.*;
public class Txt {
public static void main(String[] args) {
readFile();
writeFile();
copyFile();
}
/**
* TXT
*/
public static void readFile() {
try {
/**
* , catch , throw;
* close();
* , ;
*/
FileInputStream Ins = new FileInputStream("D:\\read.txt");
int i = Ins.read();
while(i!=-1) {
System.out.println(" :"+i);
i = Ins.read();
}
Ins.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* TXT
*/
public static void writeFile() {
try {
FileOutputStream fos = new FileOutputStream("D:\\write.txt");
String str = "46346assfjfi";
byte[] bt = str.getBytes(); //
fos.write(bt); //
fos.close(); //
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* TXT
*/
public static void copyFile() {
try {
FileInputStream fis = new FileInputStream("D:\\read.txt");
FileOutputStream fos = new FileOutputStream("D:\\copy.txt");
long start = System.currentTimeMillis(); //
int len;
while((len = fis.read()) !=-1) {
fos.write(len);
}
long end = System.currentTimeMillis(); //
System.out.println(" :"+(end-start)+" ");
fis.close(); //
fos.close(); //
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}