public class ReadFromFile {
/**
* 以字节为单位读取文件,常用于读二进制文件,如图片、声音、影像等文件。
*/
public static void readFileByBytes(String fileName) {
File file = new File(fileName);
InputStream in = null;
try {
System.out.println("以字节为单位读取文件内容,一次读一个字节:");
// 一次读一个字节
in = new FileInputStream(file);
int tempbyte;
while ((tempbyte = in.read()) != -1) {
System.out.write(tempbyte);
}
in.close();
} catch (IOException e) {
e.printStackTrace();
return;
}
try {
System.out.println("以字节为单位读取文件内容,一次读多个字节:");
// 一次读多个字节
byte[] tempbytes = new byte[100];
int byteread = 0;
in = new FileInputStream(fileName);
ReadFromFile.showAvailableBytes(in);
// 读入多个字节到字节数组中,byteread为一次读入的字节数
while ((byteread = in.read(tempbytes)) != -1) {
System.out.write(tempbytes, 0, byteread);
}
} catch (Exception e1) {
e1.printStackTrace();
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e1) {
}
}
}
}
/**
* 以字符为单位读取文件,常用于读文本,数字等类型的文件
*/
public static void readFileByChars(String fileName) {
File file = new File(fileName);
Reader reader = null;
try {
System.out.println("以字符为单位读取文件内容,一次读一个字节:");
// 一次读一个字符
reader = new InputStreamReader(new FileInputStream(file));
int tempchar;
while ((tempchar = reader.read()) != -1) {
// 对于windows下,\r\n这两个字符在一起时,表示一个换行。
// 但如果这两个字符分开显示时,会换两次行。
// 因此,屏蔽掉\r,或者屏蔽\n。否则,将会多出很多空行。
if (((char) tempchar) != '\r') {
System.out.print((char) tempchar);
}
}
reader.close();
} catch (Exception e) {
e.printStackTrace();
}
try {
System.out.println("以字符为单位读取文件内容,一次读多个字节:");
// 一次读多个字符
char[] tempchars = new char[30];
int charread = 0;
reader = new InputStreamReader(new FileInputStream(fileName));
// 读入多个字符到字符数组中,charread为一次读取字符数
while ((charread = reader.read(tempchars)) != -1) {
// 同样屏蔽掉\r不显示
if ((charread == tempchars.length)
&& (tempchars[tempchars.length - 1] != '\r')) {
System.out.print(tempchars);
} else {
for (int i = 0; i < charread; i++) {
if (tempchars[i] == '\r') {
continue;
} else {
System.out.print(tempchars[i]);
}
}
}
}
} catch (Exception e1) {
e1.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e1) {
}
}
}
}
/**
* 以行为单位读取文件,常用于读面向行的格式化文件
*/
public static void readFileByLines(String fileName) {
File file = new File(fileName);
BufferedReader reader = null;
try {
System.out.println("以行为单位读取文件内容,一次读一整行:");
reader = new BufferedReader(new FileReader(file));
String tempString = null;
int line = 1;
// 一次读入一行,直到读入null为文件结束
while ((tempString = reader.readLine()) != null) {
// 显示行号
System.out.println("line " + line + ": " + tempString);
line++;
}
reader.close();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e1) {
}
}
}
}
/**
* 随机读取文件内容
*/
public static void readFileByRandomAccess(String fileName) {
RandomAccessFile randomFile = null;
try {
System.out.println("随机读取一段文件内容:");
// 打开一个随机访问文件流,按只读方式
randomFile = new RandomAccessFile(fileName, "r");
// 文件长度,字节数
long fileLength = randomFile.length();
// 读文件的起始位置
int beginIndex = (fileLength > 4) ? 4 : 0;
// 将读文件的开始位置移到beginIndex位置。
randomFile.seek(beginIndex);
byte[] bytes = new byte[10];
int byteread = 0;
// 一次读10个字节,如果文件内容不足10个字节,则读剩下的字节。
// 将一次读取的字节数赋给byteread
while ((byteread = randomFile.read(bytes)) != -1) {
System.out.write(bytes, 0, byteread);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (randomFile != null) {
try {
randomFile.close();
} catch (IOException e1) {
}
}
}
}
/**
* 显示输入流中还剩的字节数
*/
private static void showAvailableBytes(InputStream in) {
try {
System.out.println("当前字节输入流中的字节数为:" + in.available());
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
String fileName = "C:/temp/newTemp.txt";
ReadFromFile.readFileByBytes(fileName);
ReadFromFile.readFileByChars(fileName);
ReadFromFile.readFileByLines(fileName);
ReadFromFile.readFileByRandomAccess(fileName);
}
}
5、将内容追加到文件尾部
public class AppendToFile {
/**
* A方法追加文件:使用RandomAccessFile
*/
public static void appendMethodA(String fileName, String content) {
try {
// 打开一个随机访问文件流,按读写方式
RandomAccessFile randomFile = new RandomAccessFile(fileName, "rw");
// 文件长度,字节数
long fileLength = randomFile.length();
//将写文件指针移到文件尾。
randomFile.seek(fileLength);
randomFile.writeBytes(content);
randomFile.close();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* B方法追加文件:使用FileWriter
*/
public static void appendMethodB(String fileName, String content) {
try {
//打开一个写文件器,构造函数中的第二个参数true表示以追加形式写文件
FileWriter writer = new FileWriter(fileName, true);
writer.write(content);
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
String fileName = "C:/temp/newTemp.txt";
String content = "new append!";
//按方法A追加文件
AppendToFile.appendMethodA(fileName, content);
AppendToFile.appendMethodA(fileName, "append end. \n");
//显示文件内容
ReadFromFile.readFileByLines(fileName);
//按方法B追加文件
AppendToFile.appendMethodB(fileName, content);
AppendToFile.appendMethodB(fileName, "append end. \n");
//显示文件内容
ReadFromFile.readFileByLines(fileName);
}
}
分享到:
相关推荐
在IT领域,文件读写是基础且至关重要的操作,它涉及到程序与数据的交互,无论是存储用户输入,保存程序状态,还是处理数据,都离不开文件的读取和写入。以下将详细介绍关于“读取文件操作”的核心知识点,并结合可能...
在Java编程语言中,按顺序读取文件是基础且重要的操作。这通常涉及到使用I/O流(Input/Output Stream)来处理文件数据。本篇文章将深入探讨如何在Java中实现按顺序读取文件,以及涉及的相关知识点。 首先,Java提供...
在这个改进版本中,我们使用了一个循环来分块读写文件,这样可以有效降低内存占用,适合处理大型文件。 总结,Delphi中的`TFileStream`提供了方便的文件流操作,通过它我们可以高效地读取、写入文件。结合字节数组...
本文将详细介绍如何在SQL Server环境下读取与写入服务器上的文件,包括使用OLE自动化对象(如`Scripting.FileSystemObject`)进行文件操作的方法以及通过系统扩展存储过程`xp_cmdshell`执行外部命令来读写文件的方式...
### 探寻C++最快的读取文件的方案:C++ IO优化 在计算机编程领域,尤其是在需要处理大量数据的应用场景中,文件的读取速度往往成为制约程序性能的关键因素之一。本文将通过一系列实验对比不同读取方法的速度,旨在...
如果需要同时读写文件,可以使用`fstream`类。例如: ```cpp std::fstream file("test.txt", std::ios::in | std::ios::out); if (!file) { std::cerr !" ; return -1; } // 写入 file.seekp(0, std::ios:...
在Java编程中,读写文件是一项基础且重要的任务,...以上就是关于“Java读写文件(txt)”的知识点,包括文件的读取、内容转换、正则匹配以及文件的写入。希望这些内容能帮助你理解和掌握Java在文件操作上的基本技能。
`fopen()`函数用于打开一个文件,`fclose()`用于关闭已打开的文件,`fread()`和`fwrite()`用于读写文件内容,而`fprintf()`和`fscanf()`则用于格式化输入和输出。 1. **打开文件**: 使用`fopen()`函数打开文件,...
以下是对C#读写文件摘要信息的详细说明。 首先,我们需要了解什么是文件摘要信息。在Windows操作系统中,文件摘要信息通常包括文件名、位置、大小、创建时间、修改时间和文件的描述等。这些信息可以通过`System.IO....
Java提供了多种类型的输入流(InputStream)和输出流(OutputStream)用于读写文件。在处理文本文件时,通常会用到Reader和Writer类及其子类,因为它们支持字符流操作,更符合人类语言的处理方式。 1. **读取文件**...
文件读写示例代码分析 #### 文件读取过程 在给定的代码片段中,首先使用`$fopen`函数打开一个二进制文件,并将文件句柄赋值给变量`file`。接着通过`$fread`函数将文件中的数据读取到数组`file_date`中。读取完成后...
本篇文章将详细探讨如何在CODESYS中读取TXT文件,这对于数据记录、日志存储或与上位机交互等应用十分常见。 首先,我们需要了解CODESYS中的文件系统访问。在CODESYS中,文件操作通常通过“File Service”库来实现,...
在Android平台上,对SD卡(外部存储)进行读写文件是常见的操作,尤其对于需要存储大量数据或资源的应用来说更是必不可少。本实例将探讨如何在Android应用中实现SdCard的读取和写入功能,这涉及到Android的权限管理...
用于读写文件的类,比较方便!
本实例"实例70读写文件.rar"着重介绍了如何在编程中执行文件写入的操作,以及相关的文件读写知识。 首先,我们来看"写文件"这一主题。在编程中,写文件通常涉及到以下几个步骤: 1. 打开文件:使用特定的函数,如...
在Linux内核编程中,有时候需要直接在内核空间中读写文件,这通常发生在调试驱动程序时。由于内核环境中没有标准C库的支持,必须使用内核提供的特定函数来实现这一目标。以下是对主要涉及的函数的详细解释: 1. **...
### VBS实现循环读写文件并检查 #### 知识点概述 本篇文章将详细介绍如何使用VBS(Visual Basic Script)实现文件的循环创建、读取与写入,并且能够进行回显检查来验证文件是否正确创建。文章将从VBS的基础概念...
本文将深入探讨如何使用Java IO在Android内部存储中进行读写文件操作。 首先,了解Android内部存储的结构是至关重要的。每个应用程序都有自己的数据目录,可以通过`Context`对象的`getFilesDir()`方法获取。这个...
C语言读取与写入文件源码,C语言读写文件源码 在C语言中,文件的读写操作通常使用 库中的函数来完成,主要包括 fopen() fclose() fread() fwrite() fseek() ftell() 和 fscanf() fprintf() 函数来写入字符串到文件,...