java的io简单操作
来源:互联网 发布:国际银行数据 编辑:程序博客网 时间:2024/05/01 04:56
import java.io.*;/** * Created by bruce on 2017/2/15. */public class Test { public static void main(String[] args) { File file = createNewFile(); String content = "hello world";// writeStrToFile(file, content); String readStr = readStrFromFile(file); System.out.println(readStr); } /** * 从file读取字符串 * * @param file * @return */ private static String readStrFromFile(File file) { String content = null; if (file.exists()) { FileInputStream fileInputStream = null; try { fileInputStream = new FileInputStream(file); //创建一个长度为1024的竹筒 byte[] bbuf = new byte[1024]; //用于保存实际读取的字节数 int hasRead = 0; //使用循环来重复“取水”的过程 while ((hasRead = fileInputStream.read(bbuf)) > 0) { //取出"竹筒"中(字节),将字节数组转成字符串输入 content = new String(bbuf, 0, hasRead); System.out.println(content); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { try { fileInputStream.close(); } catch (IOException e) { e.printStackTrace(); } } } else { new Throwable("文件不存在"); } return content; } /** * 在本地创建一个txt文件 * * @return */ private static File createNewFile() { File file = new File("e:\\java", "yang.txt"); if (!file.exists()) { try { file.createNewFile(); } catch (IOException e) { e.printStackTrace(); } } return file; } /** * 往文件里面写入字符串 * * @param file * @param content */ private static void writeStrToFile(File file, String content) { byte[] bytes = null; //建立输出字节流 FileOutputStream fos = null; try { bytes = content.getBytes(); fos = new FileOutputStream(file); //用FileOutputStream 的write方法写入字节数组 fos.write(bytes); System.out.println("写入成功"); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); }finally { //为了节省IO流的开销,需要关闭 try { fos.close(); } catch (IOException e) { e.printStackTrace(); } } }}
0 0
- java的io简单操作
- java IO简单操作
- Java的一些简单的IO操作!!
- java 关于IO的简单操作
- 简单的Java IO操作 修改文件名称
- 简单的io操作
- 简单的io操作
- JAVA 的IO操作(五)简单文件复制
- java实现简单的IO字节流读写操作
- 简单的JAVA IO
- Java的IO操作
- java的IO操作
- Java的IO操作
- JAVA的IO操作
- java的io操作
- Java的IO操作
- Java IO的操作
- java的IO操作
- CUDA安装后路径不全导致TensorFlow MNIST例子运行中PyThon发生异常
- js keycode对照表
- 【LeetCode-Java】54. Spiral Matrix+59. Spiral Matrix II
- 一行代码搞定Android 6.0动态权限申请
- 分布式数据库概述
- java的io简单操作
- 基础部分--机器码篇
- hibernate配置多对一的关系的时候,从多方删除信息报错
- Android app跳转QQ加人聊天或者加群
- java中long类型转换为int类型
- 447. Number of Boomerangs
- Java常用面试题17 计算文件中指定字符出现的次数
- Java多线程-工具篇-BlockingQueue
- Android中ScrollView和WebView滑动冲突