Java读写txt或doc文件

来源:互联网 发布:控制网络与现场总线 编辑:程序博客网 时间:2024/05/17 23:21
import java.io.BufferedReader;import java.io.File;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStreamReader;import java.io.UnsupportedEncodingException;public class Main {public static void main(String[] args) {Main main = new Main();//main.writeFile("D:\\test\\f1.txt");//main.writeFile("D:\\test\\f2.doc");//main.readFile("D:\\test\\f1.txt");/////读写txt  doc文件都可以main.readFile("D:\\test\\f2.doc");}// mainpublic void writeFile(String path) {try {FileOutputStream fos = new FileOutputStream(path);//System.out.println("2222".getBytes());fos.write("字符串写入文件".getBytes()); // //直接覆盖 内容是执行最后一次的内容fos.close();System.out.println("写入成功");} catch (FileNotFoundException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}public void readFile(String path) {File file = new File(path);if (file.exists() && file.isFile()) {try {BufferedReader buf = new BufferedReader(new InputStreamReader(new FileInputStream(path),"GBK"));////UTF-8是乱码  ////GBK中文String str = "";try {while ((str = buf.readLine()) != null) {System.out.println(str);}} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}} catch (FileNotFoundException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (UnsupportedEncodingException e1) {// TODO Auto-generated catch blocke1.printStackTrace();}} else {System.out.println("文件不存在");}}// /readFile}
可以自己新建文件试试,我就不上传图片了,
0 0
原创粉丝点击