Java文件读写

Java中I/O流对文件的读写有很多种方法,百度后主要看了以下三种

第一种方式:使用FileWriter和FileReader,对文件内容按字符读取,代码如下

String dir = "E:\\soft\\aaa\\a.txt";
File file = new File(dir);
//如果文件不存在,创建文件
if (!file.exists())
file.createNewFile();
//创建FileWriter对象
FileWriter writer = new FileWriter(file);
//向文件中写入内容
writer.write("the first way to write and read");
writer.flush();
writer.close(); //创建FileReader对象,读取文件中的内容
FileReader reader = new FileReader(file);
char[] ch = new char[100];
reader.read(ch);
for(char c:ch) {
System.out.print(c);
}
System.out.println();
reader.close();

第二种方式:使用包装类BuffredReader和BufferedWriter,对文件内容进行整行读取,代码如下

String dir = "E:\\soft\\aaa\\b.txt";
File file = new File(dir);
//如果文件不存在,创建文件
if (!file.exists())
file.createNewFile();
//创建BufferedWriter对象并向文件写入内容
BufferedWriter bw = new BufferedWriter(new FileWriter(file));
//向文件中写入内容
bw.write("the second way to write and read");
bw.flush();
bw.close();
//创建BufferedReader读取文件内容
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
while ((line=br.readLine())!=null) {
System.out.println(line);
}
br.close();

第三种方式:使用FileInputStream和FileOutputStream,这种方法以字节的形式写入文件,读取文件时先读取字节数组,再将字节数组转换为字符串形式,代码如下:

String dir = "E:\\soft\\aaa\\c.txt";
File file = new File(dir);
//如果文件不存在,创建文件
if (!file.exists())
file.createNewFile();
//创建FileOutputStream对象,写入内容
FileOutputStream fos = new FileOutputStream(file);
//向文件中写入内容
fos.write("the third way to write and read".getBytes());
fos.close();
//创建FileInputStream对象,读取文件内容
FileInputStream fis = new FileInputStream(file);
byte[] bys = new byte[100];
while (fis.read(bys, 0, bys.length)!=-1) {
//将字节数组转换为字符串
System.out.println(new String(bys));
}
fis.close();

类中的整体代码:

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException; public class FileRW { //第一种方式:使用FileWriter和FileReader
public void firstWay() throws IOException {
String dir = "E:\\soft\\aaa\\a.txt";
File file = new File(dir);
//如果文件不存在,创建文件
if (!file.exists())
file.createNewFile();
//创建FileWriter对象
FileWriter writer = new FileWriter(file);
//向文件中写入内容
writer.write("the first way to write and read");
writer.flush();
writer.close(); //创建FileReader对象,读取文件中的内容
FileReader reader = new FileReader(file);
char[] ch = new char[100];
reader.read(ch);
for(char c:ch) {
System.out.print(c);
}
System.out.println();
reader.close();
} //第二种方式:使用BuffredReader和BufferedWriter
public void secondWay() throws IOException {
String dir = "E:\\soft\\aaa\\b.txt";
File file = new File(dir);
//如果文件不存在,创建文件
if (!file.exists())
file.createNewFile();
//创建BufferedWriter对象并向文件写入内容
BufferedWriter bw = new BufferedWriter(new FileWriter(file));
//向文件中写入内容
bw.write("the second way to write and read");
bw.flush();
bw.close();
//创建BufferedReader读取文件内容
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
while ((line=br.readLine())!=null) {
System.out.println(line);
}
br.close();
} //第三种方式:使用FileInputStream和FileOutputStream
public void thirdWay() throws IOException {
String dir = "E:\\soft\\aaa\\c.txt";
File file = new File(dir);
//如果文件不存在,创建文件
if (!file.exists())
file.createNewFile();
//创建FileOutputStream对象,写入内容
FileOutputStream fos = new FileOutputStream(file);
//向文件中写入内容
fos.write("the third way to write and read".getBytes());
fos.close();
//创建FileInputStream对象,读取文件内容
FileInputStream fis = new FileInputStream(file);
byte[] bys = new byte[100];
while (fis.read(bys, 0, bys.length)!=-1) {
//将字节数组转换为字符串
System.out.println(new String(bys));
}
fis.close();
} public static void main(String[] args) throws IOException {
FileRW fileRW = new FileRW();
fileRW.firstWay();
fileRW.secondWay();
fileRW.thirdWay();
}

运行结果如下:

the first way to write and read
the second way to write and read
the third way to write and read

Java中生成Json数组

示例代码


import com.google.gson.*;
public class Main{ public static void main(String[] args) {
//创建一个json对象,相当于一个容器,当然这个容器还可以套在另外一个容器里面,这个看业务需要
JsonObject jsonContainer =new JsonObject();
//为当前的json对象添加键值对
jsonContainer.addProperty("category", "nba");
jsonContainer.addProperty("team", "lakers"); //构建json数组,数组里面也是json
JsonArray arrayPlayer = new JsonArray(); //构建json数组中的对象
JsonObject player1 = new JsonObject();
player1.addProperty("name", "kobe");
player1.addProperty("height", "198cm");
player1.addProperty("weight", "115kg"); JsonObject player2 = new JsonObject();
player2.addProperty("name", "fisher");
player2.addProperty("height", "183cm");
player2.addProperty("weight", "85kg"); //将json对象添加到数组中
arrayPlayer.add(player1);
arrayPlayer.add(player2); //最后将json数组装到jsonContainer中
jsonContainer.add("player", arrayPlayer); //格式化Json数组
String jsonStr=jsonContainer.toString();
JsonParser jsonParser=new JsonParser();
JsonObject jsonObject=jsonParser.parse(jsonStr).getAsJsonObject();
Gson gson=new GsonBuilder().setPrettyPrinting().create();
System.out.println(gson.toJson(jsonObject));
}
}

运行结果

{
"category": "nba",
"team": "lakers",
"player": [
{
"name": "kobe",
"height": "198cm",
"weight": "115kg"
},
{
"name": "fisher",
"height": "183cm",
"weight": "85kg"
}
]
}

其中JsonObject生成“{}”,JsonArray生成“[]”,可使用addProperty向“{}”中添加数据,使用add向“[]”中添加数据

Java学习笔记-文件读写和Json数组的更多相关文章

  1. Java学习笔记--文件IO

    简介 对于任何程序设计语言,输入和输出(Input\Output)都是系统非常核心的功能,程序运行需要数据,而数据的获取往往需要跟外部系统进行通信,外部系统可能是文件.数据库.其他程序.网络.IO设备 ...

  2. python学习之文件读写,序列化(json,pickle,shelve)

    python基础 文件读写 凡是读写文件,所有格式类型都是字符串形式传输 只读模式(默认) r  f=open('a.txt','r')#文件不存在会报错 print(f.read())#获取到文件所 ...

  3. .net学习笔记--文件读写的几种方式

    在.net中有很多有用的类库来读写硬盘上的文件 一般比较常用的有: File:1.什么时候使用:当读写件大小不大,同时可以一次性进行读写操作的时候使用         2.不同的方式可以读写文件类型不 ...

  4. Java学习笔记(三):数组

    数组声明 java语言中,数组是一种最简单的复合数据类型.数组是有序数据的集合,数组中的每个元素具有相同的数据类型,可以用一个统一的数组名和下标来唯一地确定数组中的元素. int arr1[]; in ...

  5. java学习笔记2--数据类型、数组

    本文地址:http://www.cnblogs.com/archimedes/p/java-study-note2.html,转载请注明源地址. 1.数据类型 Java数据类型有: 原始数据类型(Pr ...

  6. Java学习笔记6(循环和数组练习题)

    1.输出100到1000的水仙花数: public class LoopTest{ public static void main(String[] args){ int bai = 0; int s ...

  7. java学习笔记16--I/O流和文件

    本文地址:http://www.cnblogs.com/archimedes/p/java-study-note16.html,转载请注明源地址. IO(Input  Output)流 IO流用来处理 ...

  8. java学习笔记13--反射机制与动态代理

    本文地址:http://www.cnblogs.com/archimedes/p/java-study-note13.html,转载请注明源地址. Java的反射机制 在Java运行时环境中,对于任意 ...

  9. java学习笔记9--内部类总结

    java学习笔记系列: java学习笔记8--接口总结 java学习笔记7--抽象类与抽象方法 java学习笔记6--类的继承.Object类 java学习笔记5--类的方法 java学习笔记4--对 ...

随机推荐

  1. 【雅思】【绿宝书错词本】List37~48

    List 37 ✔ ✔ ✔ ✔ ✔ ✔ ✔ ✔ ✔ ✔ ✔ ✔ ✔ ✔ ✔ List 38 ❤ ❤ ❤ ❤ ❤ ❤ ❤ ❤ ❤ ❤ ❤ ❤ ❤ ❤ ❤ List 39 ✔ ✔ ✔ ✔ ✔ ✔ ✔ ✔ ...

  2. go语言实现分布式锁

    本文:https://chai2010.cn/advanced-go-programming-book/ch6-cloud/ch6-02-lock.html 分布式锁 在单机程序并发或并行修改全局变量 ...

  3. 【Redis】基本数据类型及命令操作(超详细)

    一.String 1.1 概述 1.2 相关命令列表 1.3 命令示例 二.List 2.1 概述: 2.2 相关命令列表: 2.3 命令示例: 2.4 链表结构的小技巧: 三.Hashes 3.1 ...

  4. MySQL DataType--当整数列遇到小数

    初始化数据: ## 创建测试表 CREATE TABLE `tb002` ( `c1` ) NOT NULL AUTO_INCREMENT, `c2` ) DEFAULT NULL, `c3` ) D ...

  5. pip 和pip3的区别

    前言装完python3后发现库里面既有pip也有pip3,不知道它们的区别,因此特意去了解了一下. 解释先搜索了一下看到了如下的解释, 安装了python3之后,库里面既会有pip3也会有pip 1. ...

  6. tomcat的根路径设置

    今天使用postman进行springmvc的测试发现提示404错误,检查原因发现是tomcat的配置问题.这里的发布的war包的访问地址 Application Context设置为了根路径”/” ...

  7. C++(四十三) — 函数模板机制

     1.普通函数与模板函数调用原则 函数模板可以像普通函数一样被重载: 当函数模板和普通函数都符合条件时,编译器优先考虑普通函数: 但如果函数模板产生一个更好的匹配,则选择函数模板: 可以通过空模板实参 ...

  8. Fiddler使用资料-整理

    以下是一个博主写的一个系列. 随笔分类 - Fiddler   10.Fiddler中设置断点修改Response 摘要:当然Fiddler中也能修改Response 第一种:打开Fiddler 点击 ...

  9. DFS遍历拷贝所有子文件夹及目录列表 (Java版)

    如题 注意,文件夹是不能拷贝的, 需要mkdir的 文件选择合适的流进行拷贝 main测试方法 /** * 主测试类,默认将D:\\base01 下的复制到D:\\base02 * @param ar ...

  10. 1219 Vue项目创建及基础

    目录 vue项目 1. 项目创建 cmd创建 可视化创建 2. 项目启动 vue重新构建依赖 pycharm管理vue项目 3. 项目目录介绍 index.html index.js App.vue ...