io流入門級別demo

import java.io.*;

//import java.io.BufferedReader;

//import java.io.BufferedWriter;

//import java.io.File;

//import java.io.FileInputStream;

//import java.io.FileNotFoundException;

//import java.io.FileOutputStream;

//import java.io.FileReader;

//import java.io.IOException;

//import java.io.InputStreamReader;

//import java.io.OutputStream;

//import java.io.OutputStreamWriter;

//import java.io.PrintStream;


public class IODemo {

public static void main(String[] args) throws IOException

{

test();

}

public static void test() throws IOException

{

sopln("--start--");

//fileWrite(newFile("D:\\JavaCode\\day30\\day30\\src\\com\\youma\\www\\dont.txt"));

//showAllFiles("D:\\JavaCode\\day13");

copyFile("D:\\JavaCode\\day30\\day30\\src\\com\\youma\\www\\dont.txt","D:\\JavaCode\\day30\\day30\\src\\com\\youma\\www\\do.txt");

//newFile("D:\\JavaCode\\day30\\day30\\src\\com\\youma\\www\\speak.txt");

sopln("--end--");

}

//  鍵盤輸入文件內容

public static void fileWrite(File file) throws FileNotFoundException

{

BufferedReader fr = new BufferedReader(new InputStreamReader((System.in)));

OutputStreamWriter bw = new OutputStreamWriter(new FileOutputStream(file));

//File f = file;

String str = null;

try {

while((str =fr.readLine())!=null)

{

if(str.equals("over"))

break;

bw.write(str+"\r\n");

bw.flush();

}

fr.close();

bw.close();

} catch (IOException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}

public static File newFile(String dir) throws IOException

{

//String[] stri = di.split("\\.");

//sopln(stri.length);

//String str1 = stri[0];

//sopln(str1);

//String str2 = stri[1];

//sopln(str2);

File file = new File(dir);

if(!file.exists())

{

sopln("no file now set");

file.createNewFile();

}

return file;

}

public static void sopln(Object obj)

{

System.out.println(obj.toString());

}

public static void showAllFiles(String dir) throws IOException

{

File f = new File(dir);

if(!f.exists())

sopln("路徑有誤!");

else

{

File[] fil = f.listFiles();

for(File file:fil)

{

if(file.isDirectory())

showAllFiles(file.getPath());

else

sopln(file.getPath());

}

}

}

public static void copyFile(String str, String dir) throws IOException

{

File copy = newFile(dir);

File file = new File(str);

if(!file.exists())

sopln("原始路徑有誤!");

else

{

BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(file)));

BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(copy)));

String st = null;

while((st = br.readLine()) != null)

{

bw.write(st);

bw.newLine();


}

                        bw.flush();

br.close();

bw.close();

}

}

}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章