原文:http://blog.csdn.net/liuweiyuxiang/article/details/69487326

将字符串写入文件

方法一

  1. public void WriteStringToFile(String filePath) {
  2. try {
  3. File file = new File(filePath);
  4. PrintStream ps = new PrintStream(new FileOutputStream(file));
  5. ps.println("http://www.jb51.net");// 往文件里写入字符串
  6. ps.append("http://www.jb51.net");// 在已有的基础上添加字符串
  7. } catch (FileNotFoundException e) {
  8. // TODO Auto-generated catch block
  9. e.printStackTrace();
  10. }
  11. }

方法二

  1. public void WriteStringToFile2(String filePath) {
  2. try {
  3. FileWriter fw = new FileWriter(filePath, true);
  4. BufferedWriter bw = new BufferedWriter(fw);
  5. bw.append("在已有的基础上添加字符串");
  6. bw.write("abc\r\n ");// 往已有的文件上添加字符串
  7. bw.write("def\r\n ");
  8. bw.write("hijk ");
  9. bw.close();
  10. fw.close();
  11. } catch (Exception e) {
  12. // TODO Auto-generated catch block
  13. e.printStackTrace();
  14. }
  15. }

方法三

  1. public void WriteStringToFile3(String filePath) {
  2. try {
  3. PrintWriter pw = new PrintWriter(new FileWriter(filePath));
  4. pw.println("abc ");
  5. pw.println("def ");
  6. pw.println("hef ");
  7. pw.close();
  8. } catch (IOException e) {
  9. // TODO Auto-generated catch block
  10. e.printStackTrace();
  11. }
  12. }

方法四

  1. public void WriteStringToFile4(String filePath) {
  2. try {
  3. RandomAccessFile rf = new RandomAccessFile(filePath, "rw");
  4. rf.writeBytes("op\r\n");
  5. rf.writeBytes("app\r\n");
  6. rf.writeBytes("hijklllll");
  7. rf.close();
  8. } catch (IOException e) {
  9. e.printStackTrace();
  10. }
  11. }

方法五

  1. public void WriteStringToFile5(String filePath) {
  2. try {
  3. FileOutputStream fos = new FileOutputStream(filePath);
  4. String s = "http://www.jb51.netl";
  5. fos.write(s.getBytes());
  6. fos.close();
  7. } catch (Exception e) {
  8. // TODO Auto-generated catch block
  9. e.printStackTrace();
  10. }
  11. }

将文件内容读取到字符串
方法一

  1. /**
  2. * 以字节为单位读取文件,常用于读二进制文件,如图片、声音、影像等文件。
  3. * 当然也是可以读字符串的。
  4. */
  5. /* 貌似是说网络环境中比较复杂,每次传过来的字符是定长的,用这种方式?*/
  6. public String readString1()
  7. {
  8. try
  9. {
  10. //FileInputStream 用于读取诸如图像数据之类的原始字节流。要读取字符流,请考虑使用 FileReader。
  11. FileInputStream inStream=this.openFileInput(FILE_NAME);
  12. ByteArrayOutputStream bos = new ByteArrayOutputStream();
  13. byte[] buffer=new byte[1024];
  14. int length=-1;
  15. while( (length = inStream.read(buffer) != -1)
  16. {
  17. bos.write(buffer,0,length);
  18. // .write方法 SDK 的解释是 Writes count bytes from the byte array buffer starting at offset index to this stream.
  19. //  当流关闭以后内容依然存在
  20. }
  21. bos.close();
  22. inStream.close();
  23. return bos.toString();
  24. // 为什么不一次性把buffer得大小取出来呢?为什么还要写入到bos中呢? return new(buffer,"UTF-8") 不更好么?
  25. // return new String(bos.toByteArray(),"UTF-8");
  26. }
  27. }

方法二

  1. // 有人说了 FileReader  读字符串更好,那么就用FileReader吧
  2. // 每次读一个是不是效率有点低了?
  3. private static String readString2()
  4. {
  5. StringBuffer str=new StringBuffer("");
  6. File file=new File(FILE_IN);
  7. try {
  8. FileReader fr=new FileReader(file);
  9. int ch = 0;
  10. while((ch = fr.read())!=-1 )
  11. {
  12. System.out.print((char)ch+" ");
  13. }
  14. fr.close();
  15. } catch (IOException e) {
  16. // TODO Auto-generated catch block
  17. e.printStackTrace();
  18. System.out.println("File reader出错");
  19. }
  20. return str.toString();
  21. }

方法三

  1. /*按字节读取字符串*/
  2. /* 个人感觉最好的方式,(一次读完)读字节就读字节吧,读完转码一次不就好了*/
  3. private static String readString3()
  4. {
  5. String str="";
  6. File file=new File(FILE_IN);
  7. try {
  8. FileInputStream in=new FileInputStream(file);
  9. // size  为字串的长度 ,这里一次性读完
  10. int size=in.available();
  11. byte[] buffer=new byte[size];
  12. in.read(buffer);
  13. in.close();
  14. str=new String(buffer,"GB2312");
  15. } catch (IOException e) {
  16. // TODO Auto-generated catch block
  17. return null;
  18. e.printStackTrace();
  19. }
  20. return str;
  21. }

方法四

    1. /*InputStreamReader+BufferedReader读取字符串  , InputStreamReader类是从字节流到字符流的桥梁*/
    2. /* 按行读对于要处理的格式化数据是一种读取的好方式 */
    3. private static String readString4()
    4. {
    5. int len=0;
    6. StringBuffer str=new StringBuffer("");
    7. File file=new File(FILE_IN);
    8. try {
    9. FileInputStream is=new FileInputStream(file);
    10. InputStreamReader isr= new InputStreamReader(is);
    11. BufferedReader in= new BufferedReader(isr);
    12. String line=null;
    13. while( (line=in.readLine())!=null )
    14. {
    15. if(len != 0)  // 处理换行符的问题
    16. {
    17. str.append("\r\n"+line);
    18. }
    19. else
    20. {
    21. str.append(line);
    22. }
    23. len++;
    24. }
    25. in.close();
    26. is.close();
    27. } catch (IOException e) {
    28. // TODO Auto-generated catch block
    29. e.printStackTrace();
    30. }
    31. return str.toString();
    32. }

Java将字符串写入文件与将文件内容读取到字符串的更多相关文章

  1. C#文件操作之把字符串取到文本文件及把文本文件读取到字符串中

    一.把字符串读取到文本文件中 using (FileStream fs = new FileStream(Path, FileMode.OpenOrCreate))//把json读到一个文本中 { S ...

  2. 把xml格式的字符串写入到一个xml文件中

    package demo; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; impo ...

  3. java 注解方式 写入数据到Excel文件中

    之前有写过一点关于java实现写Excel文件的方法,但是现在看来,那种方式用起来不是太舒服,还很麻烦.所以最近又参考其他,就写了一个新版,用起来不要太爽. 代码不需要解释,惯例直接贴下来: publ ...

  4. PHP fwrite 函数:将字符串写入文件(追加与换行)(转)

    PHP fwrite() fwrite() 函数用于向文件写入字符串,成功返回写入的字符数,否则返回 FALSE . 语法: int fwrite( resource handle, string s ...

  5. 字符串写入txt文件

    将字符串写入C盘txt文件里 File.AppendAllText(@"C:\" + DateTime.Now.ToString("HHmmss") + &qu ...

  6. Python 基础之文件操作与文件的相关函数

    一.文件操作 fp =open("文件名",mode="采用的模式",encoding="使用什么编码集")fp 这个变量接受到open的返 ...

  7. Java 创建文件夹和文件,字符串写入文件,读取文件

    两个函数如下: TextToFile(..)函数:将字符串写入给定文本文件: createDir(..)函数:创建一个文件夹,有判别是否存在的功能. public void TextToFile(fi ...

  8. Java基础之写文件——将多个字符串写入到文件中(WriteProverbs)

    控制台程序,将一系列有用的格言写入到文件中. 本例使用通道把不同长度的字符串写入到文件中,为了方便从文件中恢复字符串,将每个字符串的长度写入到文件中紧靠字符串本身前面的位置,这可以告知在读取字符串之前 ...

  9. Java读取、写入、处理Excel文件中的数据(转载)

    原文链接 在日常工作中,我们常常会进行文件读写操作,除去我们最常用的纯文本文件读写,更多时候我们需要对Excel中的数据进行读取操作,本文将介绍Excel读写的常用方法,希望对大家学习Java读写Ex ...

随机推荐

  1. webview loadRequest

    // 所构建的NSURLRequest具有一个依赖于缓存响应的特定策略,cachePolicy取得策略,timeoutInterval取得超时值 [self.yourSite loadRequest: ...

  2. MyBatis根据数组、集合查询

     foreach的主要用在构建in条件中,它可以在SQL语句中进行迭代一个集合.foreach元素的属性主要有item,index,collection,open,separator,close.it ...

  3. 坐标转换——GCJ-02

    WGS84(World Geodetic System 1984),是为GPS 全球定位系统 使用而建立的坐标系统GCJ-02,我国在WGS84的基础上加密得到BD-09,百度坐标在GCJ-02基础上 ...

  4. Java-贪心算法

    1. 什么是贪心算法? 贪心算法,又称贪婪算法(Greedy Algorithm),是指在对问题求解时,总是做出在当前看来是最好的选择.也就是说,不从整体最优解出发来考虑,它所做出的仅是在某种意义上的 ...

  5. leetcode 之Reverse Linked List II(15)

    这题用需要非常细心,用头插法移动需要考虑先移动哪个,只需三个指针即可. ListNode *reverseList(ListNode *head, int m, int n) { ListNode d ...

  6. hive-group by的时候把两个字段变成map

    源表结构: pcgid               string mobilegid           string value               double 测试数据如下: p1 m1 ...

  7. 使用Guava retryer优雅的实现接口重调机制

    API 接口调用异常, 网络异常在我们日常开发中经常会遇到,这种情况下我们需要先重试几次调用才能将其标识为错误并在确认错误之后发送异常提醒.guava-retry可以灵活的实现这一功能.Guava r ...

  8. redis之(五)redis的散列类型的命令

    [一]赋值与取值 -->命令:HSET key field value   -->往某个key的某个属性设置值 -->命令:HGET key field   --> 获取某个k ...

  9. 从徐飞的文章《Web应用的组件化开发(一)中窥视web应用开发的历史

    Web应用的组件化开发(一) 原文来自 徐飞 基本思路 1. 为什么要做组件化? 无论前端也好,后端也好,都是整个软件体系的一部分.软件产品也是产品,它的研发过程也必然是有其目的.绝大多数软件产品是追 ...

  10. 6.Spark streaming技术内幕 : Job动态生成原理与源码解析

    原创文章,转载请注明:转载自 周岳飞博客(http://www.cnblogs.com/zhouyf/)   Spark streaming 程序的运行过程是将DStream的操作转化成RDD的操作, ...