首页 > 编程语言 >java读写txt

java读写txt

时间:2023-08-08 22:37:46浏览次数:32  
标签:null java String 读写 io import new txt



新建项目 类

java读写txt_java

java读写txt_java_02


得到结构如下:

java读写txt_输入流_03


TestIo类中的代码:

package Test;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;

public class TestIo {

	private static final DateFormat DATE_FORMAT = new SimpleDateFormat(
			"yyyy-MM-dd");
	
	public static void writeToFile(String fileName, String content) {
		String time = DATE_FORMAT.format(Calendar.getInstance().getTime());
		
		File dirFile = null;
		try {
			dirFile = new File("e:\\" + time);
			if (!(dirFile.exists()) && !(dirFile.isDirectory())) {
				boolean creadok = dirFile.mkdirs();
				if (creadok) {
					System.out.println(" ok:创建文件夹成功! ");
				} else {
					System.out.println(" err:创建文件夹失败! ");
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		String fullPath = dirFile + "/" + fileName + ".txt";
		write(fullPath, content);
	}

	/**
	 * 写文件
	 * 
	 * @param path
	 * @param content
	 */
	public static boolean write(String path, String content) {
		String s = new String();
		String s1 = new String();
		BufferedWriter output = null;
		try {
			File f = new File(path);
			if (f.exists()) {
			} else {
				System.out.println("文件不存在,正在创建...");
				if (f.createNewFile()) {
					System.out.println("文件创建成功!");
				} else {
					System.out.println("文件创建失败!");
				}
			}
			BufferedReader input = new BufferedReader(new FileReader(f));
			while ((s = input.readLine()) != null) {
				s1 += s + "\n";
			}
			System.out.println("原文件内容:" + s1);
			input.close();
			s1 += content;
			output = new BufferedWriter(new FileWriter(f));
			output.write(s1);
			output.flush();
			return true;
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		} finally {
			if (output != null) {
				try {
					output.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}
	
	
	
	public static String readFile(String str) {
		File file = new File(str);
		String line;
		InputStreamReader isr= null;
		try {
			isr = new InputStreamReader(new FileInputStream(file), "utf-8");  
			BufferedReader in = new BufferedReader(isr);// 包装文件输入流,可整行读取
			StringBuilder sb = new StringBuilder();
			while ((line = in.readLine()) != null) {
				sb.append(line);
				
			}
			return sb.toString();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
			return null;
		}// 创建文件输入流
		catch (IOException e) {
			e.printStackTrace();
			return null;
		} finally {
			if (isr != null) {
				try {
					isr.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}
	
	
	public static void main(String[] args) {
		
	String	fileName ="test";
	String content="Tonight,we are young";
		
		writeToFile(fileName, content);
		
//	String ReadString=	readFile("e:/2013-09-11/test.txt");
//		System.out.print(ReadString);
	}
}




先写入:

显示结果:

java读写txt_txt读写_04


而且在e盘中已经生成了 文件:

java读写txt_输入流_05

java读写txt_java_06


内容如下:

java读写txt_System_07



程序读取显示如下:

java读写txt_java_08


PS:需要换行时 在字符串后加上"\r\n'



标签:null,java,String,读写,io,import,new,txt
From: https://blog.51cto.com/u_16218512/7013070

相关文章

  • perl基本语言语法(与java,c#不同的地方积累)
    连接字符串 perl用.  “hello”+"hello" 可用x号 "hello"*3 “hellohellohello”java,c#用+"hello"+"hello"运算符perl等待输入:$line=<STDIN>;或者$line=<>;未定义的字符值undef--不会报错当作数字使用时为0当作字符串使用时为空判断是否为空用defined()数组......
  • 遇到的问题------------时间格式转化时java.text.ParseException: Unparseable date:
    -时间格式转化时java.text.ParseException:Unparseabledate:""异常把String time=2013-09-22用 privatefinalstaticSimpleDateFormatsimpleDateFormat=newSimpleDateFormat("yyyy-MM-ddhh:mm:ss");simpleDateFormat.parse(time.trim()));转化时报错java.text.......
  • java解析json
    {"status":0,"message":"ok","total":2,"results":[{"name":"蓝光COCO金沙","location":{"lat":30.68754......
  • java调用百度地图web服务api-----该方法可用在js跨域请求上
    百度地图Web服务API为开发者提供http接口,即开发者通过http形式发起检索请求,获取返回json或xml格式的检索数据。用户可以基于此开发JavaScript、C#、C++、Java等语言的地图应用。api官网说明链接:http://developer.baidu.com/map/webservice.htm可用接口列举:获取相关地址提示place......
  • Spring-1-深入理解Spring XML中的依赖注入(DI):简化Java应用程序开发
    学习目标前两篇文章我们介绍了什么是Spring,以及Spring的一些核心概念,并且快速快发一个Spring项目,以及详细讲解IOC,今天详细介绍一些DI(依赖注入)能够配置setter方式注入属性值能够配置构造方式注入属性值能够理解什么是自动装配一、依赖注入(DI配置)1依赖注入方式【重点】......
  • Spring-2-深入理解Spring 注解依赖注入(DI):简化Java应用程序开发
    今日目标掌握纯注解开发依赖注入(DI)模式学习使用纯注解进行第三方Bean注入1注解开发依赖注入(DI)【重点】问题导入思考:如何使用注解方式将Bean对象注入到类中1.1使用@Autowired注解开启自动装配模式(按类型)@ServicepublicclassStudentServiceImplimplementsStuden......
  • 【JavaScript27】关于Function
    js中所有的函数都是通过Function构建的.在没有修改过原型链的情况下.以下等式是成立的.console.log(fn.proto.constructor===Function.prototype.constructor);console.log(fn.proto.constructor===Function);varfn=newFunction("console.log(123456);");//Funct......
  • 【JavaScript26】继承
    JS中实现继承,只需要改变函数的原型链即可示例functionCat(name){this.name=name;}Cat.prototype.eat_fish=function(fish){console.log(this.name,"在吃",fish);};functionBosiCat(name){this.name=name;}BosiCat.prototype.dance=functi......
  • 每日汇报 第七周第二天 JAVA复习&PTA
    今日学习:继续从网站中复习,PTA刷题时又复习了一下C++的vector用法和unordered_mapunordered_map是一个将key和value关联起来的容器,它可以高效的根据单个key值查找对应的value。key值应该是唯一的,key和value的数据类型可以不相同。unordered_map存储元素时是没有顺序的,......
  • 【JavaScript25】关于prototype
    老版本的js中是没有类的概念的.js如何构建一个对象的呢?在js中,每一个函数都可以作为构建一个对象的构造方法函数又可以被称为构造函数constructor构造器,构造方法functionPerson(name,age){//给当前对象(内存)进行初始化this.name=name;this.age......