1、创建目录/文件
Java中创建文件、目录非常容易。指定文件/目录路径,然后调用mkdir()和createNewFile()方法。
- import java.io.File;
- public class Main
- {
- public static void main(String[] args)
- {
- try {
- File dir = new File("d:\\OJ2");
- dir.mkdir();
- File file = new File(dir, "fil1");
- file.createNewFile();
- } catch (Exception e) {
- }
- }
- }
2、删除文件
调用File.delete()方法
- import java.io.File;
- public class Main
- {
- public static void main(String[] args)
- {
- try {
- File file = new File("d:/OJ2/fil1");
- if (file.delete()) {
- System.out.println(file.getName() + " deleted!");
- } else {
- System.out.println("file is not deleted.");
- }
- } catch (Exception e) {
- }
- }
- }
3、一行一行读文件
Java I/O类的数目比较多,很容易混淆什么时候用哪个。下面有两种方式以行方式读文件
方法一:
- private static void readFile1(File fin) throws IOException {
- FileInputStream fis = new FileInputStream(fin);
- //Construct BufferedReader from InputStreamReader
- BufferedReader br = new BufferedReader(new InputStreamReader(fis));
- String line = null;
- while ((line = br.readLine()) != null) {
- System.out.println(line);
- }
- br.close();
- }
方法二:
- private static void readFile2(File fin) throws IOException {
- // Construct BufferedReader from FileReader
- BufferedReader br = new BufferedReader(new FileReader(fin));
- String line = null;
- while ((line = br.readLine()) != null) {
- System.out.println(line);
- }
- br.close();
- }
这两种方法的区别之处是用什么来构造BufferedReader。方法一是用InputStreamReader,方法二是FileReader.
在Java Doc中,InputStreamReader是连接byte stream和character streams的桥梁,读取字节后,解释成字符。InputStreamReader还能处理除文件外的输入流,如网络连接、类路径资源、zip文件等。
FileReader是方便读取字符的类。该类的构造函数认为默认的字符编码和缓冲大小 是合适的。因此,如果程序运行在不同编码系统中时,不是一种好主意。
总体来说,InputStreamReader相对于FileReader是安全的选择。
4、写文件
下面的代码是写文件的代码,每次执行时,把旧文件删除,再创建新文件。这个不同于追加内容到文件。
- public static void writeFile1() throws IOException {
- File fout = new File("out.txt");
- FileOutputStream fos = new FileOutputStream(fout);
- BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(fos));
- for (int i = 0; i < 10; i++) {
- bw.write("something");
- bw.newLine();
- }
- bw.close();
- }
例子中用的是FileOutStream,你也可以用FileWriter或者PrintWriter。
用FileWriter:
- public static void writeFile2() throws IOException {
- FileWriter fw = new FileWriter("out.txt");
- for (int i = 0; i < 10; i++) {
- fw.write("something");
- }
- fw.close();
- }
用PrintWriter:
- public static void writeFile3() throws IOException {
- PrintWriter pw = new PrintWriter(new FileWriter("out.txt"));
- for (int i = 0; i < 10; i++) {
- pw.write("something");
- }
- pw.close();
- }
用OutputStreamWriter:
- public static void writeFile4() throws IOException {
- File fout = new File("out.txt");
- FileOutputStream fos = new FileOutputStream(fout);
- OutputStreamWriter osw = new OutputStreamWriter(fos);
- for (int i = 0; i < 10; i++) {
- osw.write("something");
- }
- osw.close();
- }
Java Doc:
- FileWriter is a convenience class for writing character files. The constructors of this class assume that the default character encoding and the default byte-buffer size are acceptable. To specify these values yourself, construct an OutputStreamWriter on a FileOutputStream.
- PrintWriter prints formatted representations of objects to a text-output stream. This class implements all of the print methods found in PrintStream. It does not contain methods for writing raw bytes, for which a program should use unencoded byte streams.
5、以追加的形式写文件
如果想用代码创建文件,并且删除先前的文件,可以用FileWriter.要替换已存在文件的所有内容,可以用下面的这块代码:
- FileWriter fstream = new FileWriter(loc);
其中loc表示文件路径。
要追加内容到已经存在的文件中,只需要设置第二个参数为true就行了
- FileWriter fstream = new FileWriter(loc, true);
6、文件复制
只需要调用FileUtils的方法CopyFile(File srcFile, File dstFile),代码如下:
- import java.io.IOException;
- import java.nio.file.Files;
- import java.nio.file.Path;
- import java.nio.file.Paths;
- public class FileCopyTest {
- public static void main(String[] args) {
- Path source = Paths.get("/Users/apple/Desktop/test.rtf");
- Path destination = Paths.get("/Users/apple/Desktop/copied.rtf");
- try {
- Files.copy(source, destination);
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- }
7、合并文件
- package com.programcreek;
- import java.io.BufferedReader;
- import java.io.BufferedWriter;
- import java.io.File;
- import java.io.FileInputStream;
- import java.io.FileWriter;
- import java.io.IOException;
- import java.io.InputStreamReader;
- public class MergerFiles {
- public static void main(String[] args) {
- String sourceFile1Path = "/home/programcreek/Desktop/s1";
- String sourceFile2Path = "/home/programcreek/Desktop/s2";
- String mergedFilePath = "/home/programcreek/Desktop/m";
- File[] files = new File[2];
- files[0] = new File(sourceFile1Path);
- files[1] = new File(sourceFile2Path);
- File mergedFile = new File(mergedFilePath);
- mergeFiles(files, mergedFile);
- }
- public static void mergeFiles(File[] files, File mergedFile) {
- FileWriter fstream = null;
- BufferedWriter out = null;
- try {
- fstream = new FileWriter(mergedFile, true);
- out = new BufferedWriter(fstream);
- } catch (IOException e1) {
- e1.printStackTrace();
- }
- for (File f : files) {
- System.out.println("merging: " + f.getName());
- FileInputStream fis;
- try {
- fis = new FileInputStream(f);
- BufferedReader in = new BufferedReader(new InputStreamReader(fis));
- String aLine;
- while ((aLine = in.readLine()) != null) {
- out.write(aLine);
- out.newLine();
- }
- in.close();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- try {
- out.close();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- }
8、移动文件
如果要将文件从一个目录移动另外一个目录下,就用renameTo()方法,下面就是一个例子:
- package com.programcreek;
- import java.io.File;
- public class MoveFileExample {
- public static void main(String[] args) {
- File file = new File("/home/programcreek/Desktop/s1");
- String targetDirectory = "/home/programcreek/Desktop/d3/";
- if (file.renameTo(new File(targetDirectory+ file.getName()))) {
- System.out.println("File is moved to " + targetDirectory);
- } else {
- System.out.println("Failed");
- }
- }
- }
9.合并目录
- package com.programcreek;
- import java.io.File;
- public class MergeTwoDirectories {
- public static void main(String[] args){
- String sourceDir1Path = "/home/programcreek/Desktop/d1";
- String sourceDir2Path = "/home/programcreek/Desktop/d2";
- File dir1 = new File(sourceDir1Path);
- File dir2 = new File(sourceDir2Path);
- mergeTwoDirectories(dir1, dir2);
- }
- public static void mergeTwoDirectories(File dir1, File dir2){
- String targetDirPath = dir1.getAbsolutePath();
- File[] files = dir2.listFiles();
- for (File file : files) {
- file.renameTo(new File(targetDirPath+File.separator+file.getName()));
- System.out.println(file.getName() + " is moved!");
- }
- }
- }
10.遍历目录
- import java.io.File;
- public class Main
- {
- public static void main(String[] args)
- {
- try {
- File[] files = new File("d:/OJ").listFiles();
- showFiles(files);
- } catch (Exception e) {
- }
- }
- private static void showFiles(File[] files)
- {
- for (File file : files) {
- if (file.isDirectory()) {
- System.out.println("Directory:" + file.getName());
- showFiles(file.listFiles());
- } else {
- System.out.println("File:" + file.getName());
- }
- }
- }
- }