java 二进制 文件比较_Java中对文件的读写操作之比较

Java 中对文件的读写操作之比较

作者:Jeru Liu

日期:November 29,2000

版本:1.0

纪念在chinaasp积分过一百呕心原创一篇(Java 中对文件的读写操作之比较)拿分好难呀,555~~~,不知道那些几千分的老妖们是怎么灌水的。

Java 对文件进行读写操作的例子很多,让初学者感到十分困惑,我觉得有必要将各种方法进行

一次分析,归类,理清不同方法之间的异同点。

一.在 JDK 1.0 中,通常是用 InputStream & OutputStream 这两个基类来进行读写操作的。

InputStream 中的 FileInputStream 类似一个文件句柄,通过它来对文件进行操作,类似的,在

OutputStream 中我们有 FileOutputStream 这个对象。

用FileInputStream 来读取数据的常用方法是:

FileInputStream fstream = new FileInputStream(args[0]);

DataInputStream in = new DataInputStream(fstream);

用 in.readLine() 来得到数据,然后用 in.close() 关闭输入流。

完整代码见 Example 1。

用FileOutputStream 来写入数据的常用方法是:

FileOutputStream out out = new FileOutputStream("myfile.txt");

PrintStream p = new PrintStream( out );

用 p.println() 来写入数据,然后用 p.close() 关闭输入。

完整代码见 Example 2。

二.在 JDK 1.1中,支持两个新的对象 Reader & Writer, 它们只能用来对文本文件进行操作,而

JDK1.1中的 InputStream & OutputStream 可以对文本文件或二进制文件进行操作。

用FileReader 来读取文件的常用方法是:

FileReader fr = new FileReader("mydata.txt");

BufferedReader br = new BufferedReader(fr);

用 br.readLing() 来读出数据,然后用br.close() 关闭缓存,用fr.close() 关闭文件。

完整代码见 Example 3。

用 FileWriter 来写入文件的常用方法是:

FileWriter fw = new FileWriter("mydata.txt");

PrintWriter out = new PrintWriter(fw);

在用out.print 或 out.println 来往文件中写入数据,out.print 和 out.println的唯一区别是后者写

入数据或会自动开一新行。写完后要记得 用out.close() 关闭输出,用fw.close() 关闭文件。

完整代码见 Example 4。

-------------------------------------------------------------- following is the source code of examples------------------------------------------------------

Example 1:

// FileInputDemo

// Demonstrates FileInputStream and DataInputStream

import java.io.*;

class FileInputDemo {

public static void main(String args[]) {

// args.length is equivalent to argc in C

if (args.length == 1) {

try {

// Open the file that is the first command line parameter

FileInputStream fstream = new FileInputStream(args[0]);

// Convert our input stream to a DataInputStream

DataInputStream in = new DataInputStream(fstream);

// Continue to read lines while there are still some left to read

while (in.available() !=0) {

// Print file line to screen

System.out.println (in.readLine());

}

in.close();

} catch (Exception e) {

System.err.println("File input error");

}

}

else

System.out.println("Invalid parameters");

}

}

Example 2:

// FileOutputDemo

// Demonstration of FileOutputStream and PrintStream classes

import java.io.*;

class FileOutputDemo

{

public static void main(String args[])  {

FileOutputStream out; // declare a file output object

PrintStream p; // declare a print stream object

try {

// connected to "myfile.txt"

out = new FileOutputStream("myfile.txt");

// Connect print stream to the output stream

p = new PrintStream( out );

p.println ("This is written to a file");

p.close();

} catch (Exception e) {

System.err.println ("Error writing to file");

}

}

}

Example 3:

// FileReadTest.java

// User FileReader in JDK1.1 to read a file

import java.io.*;

class FileReadTest {

public static void main (String[] args) {

FileReadTest t = new FileReadTest();

t.readMyFile();

}

void readMyFile() {

String record = null;

int recCount = 0;

try {

FileReader fr = new FileReader("mydata.txt");

BufferedReader br = new BufferedReader(fr);

record = new String();

while ((record = br.readLine()) != null) {

recCount++;

System.out.println(recCount + ": " + record);

}

br.close();

fr.close();

} catch (IOException e) {

System.out.println("Uh oh, got an IOException error!");

e.printStackTrace();

}

}

}

Example 4:

// FileWriteTest.java

// User FileWriter in JDK1.1 to writer a file

import java.io.*;

class FileWriteTest {

public static void main (String[] args) {

FileWriteTest t = new FileWriteTest();

t.WriteMyFile();

}

void WriteMyFile() {

try {

FileWriter fw = new FileWriter("mydata.txt");

PrintWriter out = new PrintWriter(fw);

out.print(“hi,this will be wirte into the file!”);

out.close();

fw.close();

} catch (IOException e) {

System.out.println("Uh oh, got an IOException error!");

e.printStackTrace();

}

}

}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/506143.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

python爬虫的技能_关于 Python 爬虫可能涉及到的技能点

一.颜色捕捉import cv2import numpy as npif name main:Img cv2.imread(./da_pic.jpg)#读入一幅图像kernel_2 np.ones((2,2),np.uint8)#2x2 的卷积核kernel_3 np.ones((3,3),np.uint8)#3x3 的卷积核kernel_4 np.ones((4,4),np.uint8)#4x4 的卷积核if Img is not None:#判断…

java 远程调试spark_spark开启远程调试

一.集群环境配置#调试Master,在master节点的spark-env.sh中添加SPARK_MASTER_OPTS变量export SPARK_MASTER_OPTS"-Xdebug -Xrunjdwp:transportdt_socket,servery,suspendy,address10000"#调试Worker,在worker节点的spark-env.sh中添加SPARK_WO…

python 控件id_查看控件id的工具

在Android SDK下提供了两个工具可以来查看控件的id,在Android SDK目录下的tools字文件夹下可以找到这两个工具,hierarchyviewer.bat和uiautomatorviewer.bathierarchyviewer.bat用法介绍Hierarchy Viewer只能连接Android开发版手机或是模拟器&#xff0c…

java判断方法_Java常用的判断方法

/*** 构建长度为3的数字字符串** param number* return*/private static String constructNumber(int number) {String result String.valueOf(number);// 数字字符串长度不足三位&#xff0c;前几位均补0int length result.length();for (int i 0; i < 3 - length; i) {…

java8源代码_java8 源码解读

关键字&#xff1a;native 、transient、native &#xff1a;Java平台有个用户和本地C代码进行互操作的API&#xff0c;称为Java Native Interface (Java本地接口)。更多参考&#xff1a;https://www.cnblogs.com/KingIceMou/p/7239668.htmltransient&#xff1a;Java中transie…

web中间件_常见web中间件拿shell

1.weblogic后台页面&#xff1a;(http为7001&#xff0c;https为7002)Google关键字&#xff1a;WebLogic Server AdministrationConsole inurl:console默认的用户名密码1、用户名密码均为&#xff1a;weblogic2、用户名密码均为&#xff1a;system3、用户名密码均为&#xff1a…

java定义抽象类abarea_详解 抽象类

本人在这篇博文中要讲解的知识点&#xff0c;和本人之前的一篇博文有所关联。因为&#xff0c;“抽象类” 是按照 “自下而上” 的顺序来编写所需的类&#xff0c;而在本人之前的博文《详解 继承(上)—— 工具的抽象与分层》中讲到的 继承 则与之相反&#xff0c;按照 “自上而…

word表格图片自动适应表格大小_Excel应用实践20:使用Excel中的数据自动填写Word表格...

学习Excel技术&#xff0c;关注微信公众号&#xff1a;excelperfect我在Excel工作表中存放着数据&#xff0c;如下图1所示。图1我想将这些数据逐行自动输入到Word文档的表格中并分别自动保存&#xff0c;Word文档表格如下图2所示&#xff0c;文档名为“datafromexcel.docx”。图…

dnspod java_使用dnspod遭遇的奇特问题以及背后的原因与临时解决方法

由于园子里有不少用户在使用dnspod&#xff0c;我们觉得有必要将这两天blogjava.net域名在dsnpod遇到的奇特问题分享一下&#xff0c;以免再有人踩着这个坑。12月11日&#xff0c;我们登录到dnspod的后台时&#xff0c;大吃一惊&#xff0c;blogjava.net这个域名竟然消失了。联…

python傅里叶函数图像_python实现傅里叶级数展开的实现

傅立叶级数的介绍我就不说了&#xff0c;自己也是应用为主&#xff0c;之前一直觉得很难懂&#xff0c;但最近通过自己编程实现了一些函数的傅立叶级数展开之后对傅立叶 级数展开的概念比较清楚了(1)函数如下函数图象如下&#xff1a;代码&#xff1a;from pylab import *x mg…

kafka python教程_kafka python 指定分区消费

通过assign、subscribe两者之一为消费者设置消费的主题consumer KafkaConsumer(bootstrap_servers[127.0.0.1:9092],auto_offset_resetlatest,enable_auto_commitTrue, # 自动提交消费数据的offsetconsumer_timeout_ms 10000, # 如果1秒内kafka中没有可供消费的数据&#xff0…

python字典由什么组成_在Python中,将由关键字对组成的列表添加到字典中最简单的方法是什么?...

试试这个&#xff1a;data []with open(names.dat) as database:for line in database:if line.strip(): # skip blank linesdata.append(dict(i.split(":") for i in line.rstrip(\n).split(",")))如果您的文件是&#xff1a;^{pr2}$data将是&#xff1a…

java题霸_牛客题霸每日一题 + NC50 + Java题解

import java.util.*;/** public class ListNode {* int val;* ListNode next null;* }*/public class Solution {/**** param head ListNode类* param k int整型* return ListNode类*/public ListNode reverseKGroup (ListNode head, int k) {if (head null || head.next…

cad转dxf格式文件太大_想知道DWG、DWT、DWS和DXF是什么吗?从了解4种CAD图形格式开始吧...

原创&#xff1a;就说我在开发区常用图形文件格式盘点CAD中的图形文件格式共9种&#xff0c;其扩展名分别为&#xff1a;❶DWG – 图形或块文件❷DWT – 图形样板文件❸DWS – 图形标准文件❹DXF – 图形交换文件(ASCII 或二进制)❺DST – 图形集或图纸集文件(SHEETSET 命令)❻…

vue登录如何存储cookie_vue项目实现表单登录页保存账号和密码到cookie功能

实现功能&#xff1a;1.一周内自动登录勾选时&#xff0c;将账号和密码保存到cookie&#xff0c;下次登陆自动显示到表单内2.点击忘记密码则清空之前保存到cookie的值&#xff0c;下次登陆需要手动输入次要的就不说了直接上主要的代码html部分登陆帮助一周内自动登录忘记密码&a…

usb协议规范_USB连接标准接口简述发布

制程工艺材料类USB为Universal Series Bus (通用序列总线)的缩写,是一种串行通讯协议(sereal protocol),它负责实体层和链接层的建立。它可以支持慢速的数据传输(如鼠标、键盘、游戏摇杆等)也支持快速的数字压缩影音信息。普通的USB2.0版本以下有两对线&#xff0c;分别用来传输…

java urlencode php_PHP如何使用urlencode()函数进行url编码?(代码示例)

urlencode()函数是PHP中的一个内置函数&#xff0c;用于对url进行编码。下面本篇文章就来给大家介绍一些urlencode()函数的用法&#xff0c;让大家了解urlencode()函数是如何对url进行编码的&#xff0c;希望对大家有所帮助。【视频教程推荐&#xff1a;PHP教程】urlencode()函…

python视频网站分类_媒资分类_Python SDK_服务端SDK_视频点播 - 阿里云

初始化客户端使用前请先初始化客户端&#xff0c;请参见创建分类调用AddCategory接口&#xff0c;完成创建分类功能。接口参数和返回字段请参见from aliyunsdkvod.request.v20170321 import AddCategoryRequestdef add_category(clt, cateName, parentId-1):request AddCatego…

为什么java需要静态类_java – 为什么OOP中静态类的最佳实践有所不同?

我目前正在阅读有关Java最佳实践的内容,我发现根据this book,我们必须支持非静态的静态类.我记得在C#最佳实践中,我们必须根据Dennis Doomen的C#3.0,4.0和5.0编码指南来避免这种情况&#xff1a;AV1008 – Avoid static classesWith the exception of extension method contain…

光电转换模块_光模块:PIN光电二极管和APD光电二极管

在前面的文章中我们介绍了光模块的基本结构&#xff0c;包括TOSA、ROSA以及BOSA。今天我们接着介绍ROSA光器件的光电探测器。光模块接收端能正确识别信号并完成光电转换&#xff0c;就需要光电探测器&#xff0c;光电探测器通过检测出照射在其上面的光功率&#xff0c;从而并完…