Java写内容到本地文件

Java程序写内容到本地文件,代码如下:

导包部分:
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;

public class FileUtils {

public static void main(String args[]) {
	writeFile();
}
public static void writeFile() {
	FileWriter fileWriter = null;
	BufferedWriter bw = null;
	try {
		// The path of target file must be existed, target file can not be existed 
		File testFile = new File("E:\\Test_JAVAProgram\\TestWriteFile\\TestWriteFile.txt");
		System.out.println("This is a sample to write file");
		fileWriter = new FileWriter(testFile);
		bw = new BufferedWriter(fileWriter);
		String contentStr = "Hello World!";
		bw.write(contentStr);
		// Get new line
		bw.append(System.getProperty("line.separator"));
		bw.append("This is a sample to write file!");
		// Need to add this statement
		bw.flush();
	}catch(Exception e) {
		e.toString();
	}finally {
		if(bw != null) {
			try {
				bw.close();
			}catch(Exception e) {
				e.toString();
			}
		}
		if(fileWriter != null) {
			try {
				fileWriter.close();
			}catch(Exception e) {
				e.toString();
			}
		}
	}
}

}

	public static void writeFile() {
    
    
		FileWriter fileWriter = null;
		BufferedWriter bw = null;
		try {
    
    
			// The path of target file must be existed, target file can not be existed 
			File testFile = new File("E:\\Test_JAVAProgram\\TestWriteFile\\TestWriteFile.txt");
			System.out.println("This is a sample to write file");
			fileWriter = new FileWriter(testFile);
			bw = new BufferedWriter(fileWriter);
			String contentStr = "Hello World!";
			bw.write(contentStr);
			// Get new line
			bw.append(System.getProperty("line.separator"));
			bw.append("This is a sample to write file!");
			// Need to add this statement
			bw.flush();
		}catch(Exception e) {
    
    
			e.toString();
		}finally {
    
    
			if(bw != null) {
    
    
				try {
    
    
					bw.close();
				}catch(Exception e) {
    
    
					e.toString();
				}
			}
			if(fileWriter != null) {
    
    
				try {
    
    
					fileWriter.close();
				}catch(Exception e) {
    
    
					e.toString();
				}
			}
		}
	}

这样就完成了写内容到本地文件。

猜你喜欢

转载自blog.csdn.net/weixin_42488909/article/details/108810173