Java将字符串写入文件与将文件内容读取到字符串
原文:http://blog.csdn.net/liuweiyuxiang/article/details/69487326
将字符串写入文件
方法一
- public void WriteStringToFile(String filePath) {
- try {
- File file = new File(filePath);
- PrintStream ps = new PrintStream(new FileOutputStream(file));
- ps.println("http://www.jb51.net");// 往文件里写入字符串
- ps.append("http://www.jb51.net");// 在已有的基础上添加字符串
- } catch (FileNotFoundException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
方法二
- public void WriteStringToFile2(String filePath) {
- try {
- FileWriter fw = new FileWriter(filePath, true);
- BufferedWriter bw = new BufferedWriter(fw);
- bw.append("在已有的基础上添加字符串");
- bw.write("abc\r\n ");// 往已有的文件上添加字符串
- bw.write("def\r\n ");
- bw.write("hijk ");
- bw.close();
- fw.close();
- } catch (Exception e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
方法三
- public void WriteStringToFile3(String filePath) {
- try {
- PrintWriter pw = new PrintWriter(new FileWriter(filePath));
- pw.println("abc ");
- pw.println("def ");
- pw.println("hef ");
- pw.close();
- } catch (IOException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
方法四
- public void WriteStringToFile4(String filePath) {
- try {
- RandomAccessFile rf = new RandomAccessFile(filePath, "rw");
- rf.writeBytes("op\r\n");
- rf.writeBytes("app\r\n");
- rf.writeBytes("hijklllll");
- rf.close();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
方法五
- public void WriteStringToFile5(String filePath) {
- try {
- FileOutputStream fos = new FileOutputStream(filePath);
- String s = "http://www.jb51.netl";
- fos.write(s.getBytes());
- fos.close();
- } catch (Exception e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
将文件内容读取到字符串
方法一
- /**
- * 以字节为单位读取文件,常用于读二进制文件,如图片、声音、影像等文件。
- * 当然也是可以读字符串的。
- */
- /* 貌似是说网络环境中比较复杂,每次传过来的字符是定长的,用这种方式?*/
- public String readString1()
- {
- try
- {
- //FileInputStream 用于读取诸如图像数据之类的原始字节流。要读取字符流,请考虑使用 FileReader。
- FileInputStream inStream=this.openFileInput(FILE_NAME);
- ByteArrayOutputStream bos = new ByteArrayOutputStream();
- byte[] buffer=new byte[1024];
- int length=-1;
- while( (length = inStream.read(buffer) != -1)
- {
- bos.write(buffer,0,length);
- // .write方法 SDK 的解释是 Writes count bytes from the byte array buffer starting at offset index to this stream.
- // 当流关闭以后内容依然存在
- }
- bos.close();
- inStream.close();
- return bos.toString();
- // 为什么不一次性把buffer得大小取出来呢?为什么还要写入到bos中呢? return new(buffer,"UTF-8") 不更好么?
- // return new String(bos.toByteArray(),"UTF-8");
- }
- }
方法二
- // 有人说了 FileReader 读字符串更好,那么就用FileReader吧
- // 每次读一个是不是效率有点低了?
- private static String readString2()
- {
- StringBuffer str=new StringBuffer("");
- File file=new File(FILE_IN);
- try {
- FileReader fr=new FileReader(file);
- int ch = 0;
- while((ch = fr.read())!=-1 )
- {
- System.out.print((char)ch+" ");
- }
- fr.close();
- } catch (IOException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- System.out.println("File reader出错");
- }
- return str.toString();
- }
方法三
- /*按字节读取字符串*/
- /* 个人感觉最好的方式,(一次读完)读字节就读字节吧,读完转码一次不就好了*/
- private static String readString3()
- {
- String str="";
- File file=new File(FILE_IN);
- try {
- FileInputStream in=new FileInputStream(file);
- // size 为字串的长度 ,这里一次性读完
- int size=in.available();
- byte[] buffer=new byte[size];
- in.read(buffer);
- in.close();
- str=new String(buffer,"GB2312");
- } catch (IOException e) {
- // TODO Auto-generated catch block
- return null;
- e.printStackTrace();
- }
- return str;
- }
方法四
- /*InputStreamReader+BufferedReader读取字符串 , InputStreamReader类是从字节流到字符流的桥梁*/
- /* 按行读对于要处理的格式化数据是一种读取的好方式 */
- private static String readString4()
- {
- int len=0;
- StringBuffer str=new StringBuffer("");
- File file=new File(FILE_IN);
- try {
- FileInputStream is=new FileInputStream(file);
- InputStreamReader isr= new InputStreamReader(is);
- BufferedReader in= new BufferedReader(isr);
- String line=null;
- while( (line=in.readLine())!=null )
- {
- if(len != 0) // 处理换行符的问题
- {
- str.append("\r\n"+line);
- }
- else
- {
- str.append(line);
- }
- len++;
- }
- in.close();
- is.close();
- } catch (IOException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- return str.toString();
- }
Java将字符串写入文件与将文件内容读取到字符串的更多相关文章
- C#文件操作之把字符串取到文本文件及把文本文件读取到字符串中
一.把字符串读取到文本文件中 using (FileStream fs = new FileStream(Path, FileMode.OpenOrCreate))//把json读到一个文本中 { S ...
- 把xml格式的字符串写入到一个xml文件中
package demo; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; impo ...
- java 注解方式 写入数据到Excel文件中
之前有写过一点关于java实现写Excel文件的方法,但是现在看来,那种方式用起来不是太舒服,还很麻烦.所以最近又参考其他,就写了一个新版,用起来不要太爽. 代码不需要解释,惯例直接贴下来: publ ...
- PHP fwrite 函数:将字符串写入文件(追加与换行)(转)
PHP fwrite() fwrite() 函数用于向文件写入字符串,成功返回写入的字符数,否则返回 FALSE . 语法: int fwrite( resource handle, string s ...
- 字符串写入txt文件
将字符串写入C盘txt文件里 File.AppendAllText(@"C:\" + DateTime.Now.ToString("HHmmss") + &qu ...
- Python 基础之文件操作与文件的相关函数
一.文件操作 fp =open("文件名",mode="采用的模式",encoding="使用什么编码集")fp 这个变量接受到open的返 ...
- Java 创建文件夹和文件,字符串写入文件,读取文件
两个函数如下: TextToFile(..)函数:将字符串写入给定文本文件: createDir(..)函数:创建一个文件夹,有判别是否存在的功能. public void TextToFile(fi ...
- Java基础之写文件——将多个字符串写入到文件中(WriteProverbs)
控制台程序,将一系列有用的格言写入到文件中. 本例使用通道把不同长度的字符串写入到文件中,为了方便从文件中恢复字符串,将每个字符串的长度写入到文件中紧靠字符串本身前面的位置,这可以告知在读取字符串之前 ...
- Java读取、写入、处理Excel文件中的数据(转载)
原文链接 在日常工作中,我们常常会进行文件读写操作,除去我们最常用的纯文本文件读写,更多时候我们需要对Excel中的数据进行读取操作,本文将介绍Excel读写的常用方法,希望对大家学习Java读写Ex ...
随机推荐
- EOS.IO技术学习
如今很火的项目EOS的学习,以下主要的内容是基于白皮书 参考: http://chainx.org/paper/index/index/id/20.html EOS.IO软件引入了一种新的块链架构,旨 ...
- 学习1:python输入输出
1. 输出 >>> print "hello world" hello world >>> print 'hello world' hello ...
- C#ActiveX控件开发
1.新建项目,选择C#,选择.NET Framework2.0,新建一个Windows窗体控件库项目,命名为ActiveXDemo; 2.右击ActiveXDem项目,选择属性——应用程序——程序集信 ...
- linux磁盘占用跟每个文件夹大小总和不符
1.一种情况是删除了大文件但是没有释放出来,因为有进程还在调用使用 最简单的方法是reboot下服务器再对比下: 2.查看服务器空间使用情况 df -h cd / du -sh *
- 利用BeanUtils工具类封装表单数据
一.BeanUtils工具类的使用 1.首先导入BeanUtils工具类的jar包 commons-beanutils-1.8.0.jar commons-logging-1.1.1.jar 2.se ...
- Java单线程多实例和多线程多实例
最近写了一个程序,是采用多线程往redis里面写入数据,想统计一下一共写了多少条数据,于是用了一个static的全局变量count来累加,这块代码抽象出来就是这样的: public class Mul ...
- php文件上传需要的配置
服务端配置(php.ini) 1.file_uploads=On //支持HTTP上传 2.upload_tmp_dir =”” //临时文件保存的目录 3.upload_max_filesize ...
- 微信小程序实战篇-图片的预览、二维码的识别
开篇 今天,做的小程序项目要求,个人中心的客服图片在用户长按时可以识别其二维码,各种翻阅查找,采坑很多,浪费了很多时间,在这里记录下需要注意的点,以及对小程序官方提供的API做一个正确和清晰的认知,希 ...
- redis之(十三)redis的三种启动方式
Part I. 直接启动 下载 官网下载 安装 tar zxvf redis-2.8.9.tar.gz cd redis-2.8.9 #直接make 编译 make #可使用root用户执行`make ...
- hdu5728
详细题解: http://blog.csdn.net/wust_zzwh/article/details/51966450 ……化简公式的能力还不够啊…… #include<bits/stdc+ ...