【JAVA】Java文件的读写

1. 写文件(PrintWriter)

读与写都要有 File 关键字的配合,如下例:

File file = new File(filepath/name);
if (file.exists()) {
	file.delete();
	file.createNewFile();
}
else
	file.createNewFile();
PrintWriter output = new PrintWriter(file);
StringBuilder sb = new StringBuilder(); 
sb = "This is a test."
output.println(sb);
output.close();
注意 StringBuilder 和 StringBuffer 是差不多的,另外,文件打开后一定配合关闭操作。另,Java 包含 I/O 操作要强制加上 throw Exception ,否则会报错。

2.读文件(Scanner)

File file = new File(filepath/name);
Scanner input = new Scanner(file);
StringBuilder Str = new StringBuilder();
while (input.hasNext()) {
  Str.append(input.NextLine)
}
input.close();

3.例子(读Java文件并写入html文件)

Java文件:

// This application displays welcome to JAVA!
public class Welcome {
	public static void main(String[] args) {
		System.out.println("Welome to JAVA!!!");
	}
}
处理程序:

package Test;

import java.io.File;
import java.io.PrintWriter;
import java.util.Scanner;

public class Ex10 {
	public static void main(String[] args) throws Exception {
//		String string = "//";
//		String string2 = "//";
//		System.out.println(string.equals("//"));
		File readFile = new File("Welcome.java");
		Scanner input = new Scanner(readFile);
		
		StringBuilder output = new StringBuilder();
		output.append("");
		output.append("");
		output.append("This is a test.");
		output.append("");
		output.append("");
		output.append("");
		
		while (input.hasNextLine()) {
			String buffer = input.nextLine();
			String[] strings = buffer.split("[ \n\t\r;,.:?!{()]");
			output.append("

"); for (int i = 0; i < strings.length; i++) { System.out.println(strings[i]); if (strings[i].equals("//")) { output.delete(output.length() - 4, output.length() - 1); output.append("

"); } else if (strings[i].equals("public") || strings[i].equals("class") || strings[i].equals("void")) { output.append(" " + strings[i] + " "); } else if (strings[i].equals("main") || strings[i].equals("Wellcome")) { output.append(" " + strings[i] + " "); } else { output.append(" " + strings[i] + " "); } } output.append("

"); } output.append(""); input.close(); File writeFlie = new File("Welcome.html"); if (writeFlie.exists()) { writeFlie.delete(); writeFlie.createNewFile(); }else { writeFlie.createNewFile(); } PrintWriter wriFile = new PrintWriter(writeFlie); wriFile.print(output); wriFile.close(); System.out.println("Done"); } }
处理结果:





你可能感兴趣的:(Java)