Java 用CRUD操作处理文件
到目前为止,使用Java程序的操作都是在提示符/终端上完成的,并没有存储在任何地方。但在软件行业中,大多数程序都是为了存储从程序中获取的信息而编写的。其中一种方法是将获取的信息存储在一个 文件 中 。
什么是Java中的文件处理 ?
文件 是一个容器,用来存储各种类型的信息。通过创建一个具有唯一名称的文件,数据被永久地存储在二级存储器中。一个文件可以由文本、图像或任何其他文件组成。
可以在文件上进行的不同操作有
- 创建一个新文件
- 打开一个现有的文件
- 从文件中读取
- 写入文件
- 移动到文件中的一个特定位置
- 关闭一个文件
在Java中可用于文件处理的不同类
- InputStream
- OutputStream
- FilterOutputStream
- FileOutputStream
- ByteArrayOutputStream
- ByteArrayInputStream
- FileInputStream
- FilterInputStream
- StringBufferInputStream
- SequenceInputStream
- BufferedOutputStream
- StringBufferInputStream
- DataOutputStream
- PrintStream
- BufferedInputStream
- DataInputStream
- PushbackInputStream
在这篇文章中,我们将学习Java ByteStreams如何使用RandomAccessFile类来执行8位(1字节)的输入和输出,该类由 writeBytes()和readBytes() 方法组成,以字节的形式写入和读取数据。
用于执行文件操作的各种方法 。
- writeBytes(String s): 将字符串作为字节序列写入文件。
- readLine(): 从该文件中读取下一行文本。
- getFilePointer(): 返回该文件中的当前偏移量。
- length(): 返回这个文件的长度,返回类型为long。
- close(): 关闭这个随机存取文件流,并释放与该流相关的任何系统资源。
- setLength(long newLength): 设置这个文件的长度。
- seek(long pos): 设置文件指针的偏移量,从这个文件的开头算起,下一次读或写发生在这个位置。
Java中的文件打开模式
值 | 意义 |
---|---|
“r” | 只为阅读而打开。调用结果对象的任何写入方法将导致抛出一个IOException。 |
“rw” | 开放供阅读和写作。如果该文件不存在,那么将尝试创建它。 |
“rws” | 开放读写,和 “rw “一样,同时要求对文件内容或元数据的每一次更新都要同步写入底层存储设备。 |
“rwd” | 与 “rw “一样,对读写开放,并且还要求对文件内容的每一次更新都要同步写入底层存储设备。 |
使用RandomAccessFile打开文件的语法
File file = new File( filename )
RandomAccessFile raf = new RandomAccessFile(file, mode)
在Java中使用文件处理的CRUD操作
例子: 考虑到你想把你朋友的联系号码记录在一个文件中。为了区分你朋友的名字和联系号码,你需要一个分隔符。要做到这一点,你需要选择一个分隔符,如’!’或’$’或一些不出现在你朋友名字里的特殊符号。然后我们将形成一个由名字、特殊符号和数字组成的字符串,插入到文件中。
文件friendsContact.txt中的联系人的语法
Name!Number
如何在Java中创建一个文件 ?
// Java program to create a file "friendsContact.txt"
// and add a new contact in the file
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.lang.NumberFormatException;
class AddFriend {
public static void main(String data[])
{
try {
// Get the name of the contact to be updated
// from the Command line argument
String newName = data[0];
// Get the number to be updated
// from the Command line argument
long newNumber = Long.parseLong(data[1]);
String nameNumberString;
String name;
long number;
int index;
// Using file pointer creating the file.
File file = new File("friendsContact.txt");
if (!file.exists()) {
// Create a new file if not exists.
file.createNewFile();
}
// Opening file in reading and write mode.
RandomAccessFile raf
= new RandomAccessFile(file, "rw");
boolean found = false;
// Checking whether the name
// of contact already exists.
// getFilePointer() give the current offset
// value from start of the file.
while (raf.getFilePointer() < raf.length()) {
// reading line from the file.
nameNumberString = raf.readLine();
// splitting the string to get name and
// number
String[] lineSplit
= nameNumberString.split("!");
// separating name and number.
name = lineSplit[0];
number = Long.parseLong(lineSplit[1]);
// if condition to find existence of record.
if (name == newName
|| number == newNumber) {
found = true;
break;
}
}
if (found == false) {
// Enter the if block when a record
// is not already present in the file.
nameNumberString
= newName + "!"
+ String.valueOf(newNumber);
// writeBytes function to write a string
// as a sequence of bytes.
raf.writeBytes(nameNumberString);
// To insert the next record in new line.
raf.writeBytes(System.lineSeparator());
// Print the message
System.out.println(" Friend added. ");
// Closing the resources.
raf.close();
}
// The contact to be updated
// could not be found
else {
// Closing the resources.
raf.close();
// Print the message
System.out.println(" Input name"
+ " does not exists. ");
}
}
catch (IOException ioe) {
System.out.println(ioe);
}
catch (NumberFormatException nef) {
System.out.println(nef);
}
}
}
输出
编译并在新创建的文件中添加联系人 。
javac AddFriend.java
java AddFriend abc 1111111111
Friend added
java AddFriend pqr 1111111111
Input name or number already exist
文件
如何在Java中读取文件 ?
// Java program to read from file "friendsContact.txt"
// and display the contacts
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.lang.NumberFormatException;
class DisplayFriends {
public static void main(String data[])
{
try {
String nameNumberString;
String name;
long number;
int index;
// Using file pointer creating the file.
File file = new File("friendsContact.txt");
if (!file.exists()) {
// Create a new file if not exists.
file.createNewFile();
}
// Opening file in reading and write mode.
RandomAccessFile raf
= new RandomAccessFile(file, "rw");
boolean found = false;
// Traversing the file
// getFilePointer() give the current offset
// value from start of the file.
while (raf.getFilePointer() < raf.length()) {
// reading line from the file.
nameNumberString = raf.readLine();
// splitting the string to get name and
// number
String[] lineSplit
= nameNumberString.split("!");
// separating name and number.
name = lineSplit[0];
number = Long.parseLong(lineSplit[1]);
// Print the contact data
System.out.println(
"Friend Name: " + name + "\n"
+ "Contact Number: " + number + "\n");
}
catch (IOException ioe)
{
System.out.println(ioe);
}
catch (NumberFormatException nef)
{
System.out.println(nef);
}
}
}
输出
编译和读取文件中的联系人 。
javac DisplayFriends.java
java DisplayFriends
Friend Name: abc
Contact Number: 1234567890
Friend Name: lmn
Contact Number: 3333333333
Friend Name: xyz
Contact Number: 4444444444
文件
如何在Java中更新一个文件 ?
// Java program to update in the file "friendsContact.txt"
// and change the number of an old contact
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.lang.NumberFormatException;
class UpdateFriend {
public static void main(String data[])
{
try {
// Get the name of the contact to be updated
// from the Command line argument
String newName = data[0];
// Get the number to be updated
// from the Command line argument
long newNumber = Long.parseLong(data[1]);
String nameNumberString;
String name;
long number;
int index;
// Using file pointer creating the file.
File file = new File("friendsContact.txt");
if (!file.exists()) {
// Create a new file if not exists.
file.createNewFile();
}
// Opening file in reading and write mode.
RandomAccessFile raf
= new RandomAccessFile(file, "rw");
boolean found = false;
// Checking whether the name
// of contact already exists.
// getFilePointer() give the current offset
// value from start of the file.
while (raf.getFilePointer() < raf.length()) {
// reading line from the file.
nameNumberString = raf.readLine();
// splitting the string to get name and
// number
String[] lineSplit
= nameNumberString.split("!");
// separating name and number.
name = lineSplit[0];
number = Long.parseLong(lineSplit[1]);
// if condition to find existence of record.
if (name == newName
|| number == newNumber) {
found = true;
break;
}
}
// Update the contact if record exists.
if (found == true) {
// Creating a temporary file
// with file pointer as tmpFile.
File tmpFile = new File("temp.txt");
// Opening this temporary file
// in ReadWrite Mode
RandomAccessFile tmpraf
= new RandomAccessFile(tmpFile, "rw");
// Set file pointer to start
raf.seek(0);
// Traversing the friendsContact.txt file
while (raf.getFilePointer()
< raf.length()) {
// Reading the contact from the file
nameNumberString = raf.readLine();
index = nameNumberString.indexOf('!');
name = nameNumberString.substring(
0, index);
// Check if the fetched contact
// is the one to be updated
if (name.equals(inputName)) {
// Update the number of this contact
nameNumberString
= name + "!"
+ String.valueOf(newNumber);
}
// Add this contact in the temporary
// file
tmpraf.writeBytes(nameNumberString);
// Add the line separator in the
// temporary file
tmpraf.writeBytes(
System.lineSeparator());
}
// The contact has been updated now
// So copy the updated content from
// the temporary file to original file.
// Set both files pointers to start
raf.seek(0);
tmpraf.seek(0);
// Copy the contents from
// the temporary file to original file.
while (tmpraf.getFilePointer()
< tmpraf.length()) {
raf.writeBytes(tmpraf.readLine());
raf.writeBytes(System.lineSeparator());
}
// Set the length of the original file
// to that of temporary.
raf.setLength(tmpraf.length());
// Closing the resources.
tmpraf.close();
raf.close();
// Deleting the temporary file
tmpFile.delete();
System.out.println(" Friend updated. ");
}
// The contact to be updated
// could not be found
else {
// Closing the resources.
raf.close();
// Print the message
System.out.println(" Input name"
+ " does not exists. ");
}
}
catch (IOException ioe) {
System.out.println(ioe);
}
catch (NumberFormatException nef) {
System.out.println(nef);
}
}
}
输出
编译并更新文件中的联系人
javac UpdateFriend.java
java UpdateFriend abc 1234567890
Friend updated.
java UpdateFriend tqr
Input name does not exists.
文件
如何在Java中删除一个文件
// Java program to delete a contact
// from the file "friendsContact.txt"
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.lang.NumberFormatException;
class DeleteFriend {
public static void main(String data[])
{
try {
// Get the name of the contact to be updated
// from the Command line argument
String newName = data[0];
String nameNumberString;
String name;
long number;
int index;
// Using file pointer creating the file.
File file = new File("friendsContact.txt");
if (!file.exists()) {
// Create a new file if not exists.
file.createNewFile();
}
// Opening file in reading and write mode.
RandomAccessFile raf
= new RandomAccessFile(file, "rw");
boolean found = false;
// Checking whether the name of contact exists.
// getFilePointer() give the current offset
// value from start of the file.
while (raf.getFilePointer() < raf.length()) {
// reading line from the file.
nameNumberString = raf.readLine();
// splitting the string to get name and
// number
String[] lineSplit
= nameNumberString.split("!");
// separating name and number.
name = lineSplit[0];
number = Long.parseLong(lineSplit[1]);
// if condition to find existence of record.
if (name == newName) {
found = true;
break;
}
}
// Delete the contact if record exists.
if (found == true) {
// Creating a temporary file
// with file pointer as tmpFile.
File tmpFile = new File("temp.txt");
// Opening this temporary file
// in ReadWrite Mode
RandomAccessFile tmpraf
= new RandomAccessFile(tmpFile, "rw");
// Set file pointer to start
raf.seek(0);
// Traversing the friendsContact.txt file
while (raf.getFilePointer()
< raf.length()) {
// Reading the contact from the file
nameNumberString = raf.readLine();
index = nameNumberString.indexOf('!');
name = nameNumberString.substring(
0, index);
// Check if the fetched contact
// is the one to be deleted
if (name.equals(inputName)) {
// Skip inserting this contact
// into the temporary file
continue;
}
// Add this contact in the temporary
// file
tmpraf.writeBytes(nameNumberString);
// Add the line separator in the
// temporary file
tmpraf.writeBytes(
System.lineSeparator());
}
// The contact has been deleted now
// So copy the updated content from
// the temporary file to original file.
// Set both files pointers to start
raf.seek(0);
tmpraf.seek(0);
// Copy the contents from
// the temporary file to original file.
while (tmpraf.getFilePointer()
< tmpraf.length()) {
raf.writeBytes(tmpraf.readLine());
raf.writeBytes(System.lineSeparator());
}
// Set the length of the original file
// to that of temporary.
raf.setLength(tmpraf.length());
// Closing the resources.
tmpraf.close();
raf.close();
// Deleting the temporary file
tmpFile.delete();
System.out.println(" Friend deleted. ");
}
// The contact to be deleted
// could not be found
else {
// Closing the resources.
raf.close();
// Print the message
System.out.println(" Input name"
+ " does not exists. ");
}
}
catch (IOException ioe) {
System.out.println(ioe);
}
}
}
输出
编译并删除文件中的联系人
javac DeleteFriend.java
java DeleteFriend pqr
Friend deleted.
java DeleteFriend tqr
Input name does not exists.
文件
// Java program to create a file "friendsContact.txt"
// and add a new contact in the file
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.lang.NumberFormatException;
class AddFriend {
public static void main(String data[])
{
try {
// Get the name of the contact to be updated
// from the Command line argument
String newName = data[0];
// Get the number to be updated
// from the Command line argument
long newNumber = Long.parseLong(data[1]);
String nameNumberString;
String name;
long number;
int index;
// Using file pointer creating the file.
File file = new File("friendsContact.txt");
if (!file.exists()) {
// Create a new file if not exists.
file.createNewFile();
}
// Opening file in reading and write mode.
RandomAccessFile raf
= new RandomAccessFile(file, "rw");
boolean found = false;
// Checking whether the name
// of contact already exists.
// getFilePointer() give the current offset
// value from start of the file.
while (raf.getFilePointer() < raf.length()) {
// reading line from the file.
nameNumberString = raf.readLine();
// splitting the string to get name and
// number
String[] lineSplit
= nameNumberString.split("!");
// separating name and number.
name = lineSplit[0];
number = Long.parseLong(lineSplit[1]);
// if condition to find existence of record.
if (name == newName
|| number == newNumber) {
found = true;
break;
}
}
if (found == false) {
// Enter the if block when a record
// is not already present in the file.
nameNumberString
= newName + "!"
+ String.valueOf(newNumber);
// writeBytes function to write a string
// as a sequence of bytes.
raf.writeBytes(nameNumberString);
// To insert the next record in new line.
raf.writeBytes(System.lineSeparator());
// Print the message
System.out.println(" Friend added. ");
// Closing the resources.
raf.close();
}
// The contact to be updated
// could not be found
else {
// Closing the resources.
raf.close();
// Print the message
System.out.println(" Input name"
+ " does not exists. ");
}
}
catch (IOException ioe) {
System.out.println(ioe);
}
catch (NumberFormatException nef) {
System.out.println(nef);
}
}
}
// Java program to read from file "friendsContact.txt"
// and display the contacts
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.lang.NumberFormatException;
class DisplayFriends {
public static void main(String data[])
{
try {
String nameNumberString;
String name;
long number;
int index;
// Using file pointer creating the file.
File file = new File("friendsContact.txt");
if (!file.exists()) {
// Create a new file if not exists.
file.createNewFile();
}
// Opening file in reading and write mode.
RandomAccessFile raf
= new RandomAccessFile(file, "rw");
boolean found = false;
// Traversing the file
// getFilePointer() give the current offset
// value from start of the file.
while (raf.getFilePointer() < raf.length()) {
// reading line from the file.
nameNumberString = raf.readLine();
// splitting the string to get name and
// number
String[] lineSplit
= nameNumberString.split("!");
// separating name and number.
name = lineSplit[0];
number = Long.parseLong(lineSplit[1]);
// Print the contact data
System.out.println(
"Friend Name: " + name + "\n"
+ "Contact Number: " + number + "\n");
}
catch (IOException ioe)
{
System.out.println(ioe);
}
catch (NumberFormatException nef)
{
System.out.println(nef);
}
}
}
// Java program to update in the file "friendsContact.txt"
// and change the number of an old contact
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.lang.NumberFormatException;
class UpdateFriend {
public static void main(String data[])
{
try {
// Get the name of the contact to be updated
// from the Command line argument
String newName = data[0];
// Get the number to be updated
// from the Command line argument
long newNumber = Long.parseLong(data[1]);
String nameNumberString;
String name;
long number;
int index;
// Using file pointer creating the file.
File file = new File("friendsContact.txt");
if (!file.exists()) {
// Create a new file if not exists.
file.createNewFile();
}
// Opening file in reading and write mode.
RandomAccessFile raf
= new RandomAccessFile(file, "rw");
boolean found = false;
// Checking whether the name
// of contact already exists.
// getFilePointer() give the current offset
// value from start of the file.
while (raf.getFilePointer() < raf.length()) {
// reading line from the file.
nameNumberString = raf.readLine();
// splitting the string to get name and
// number
String[] lineSplit
= nameNumberString.split("!");
// separating name and number.
name = lineSplit[0];
number = Long.parseLong(lineSplit[1]);
// if condition to find existence of record.
if (name == newName
|| number == newNumber) {
found = true;
break;
}
}
// Update the contact if record exists.
if (found == true) {
// Creating a temporary file
// with file pointer as tmpFile.
File tmpFile = new File("temp.txt");
// Opening this temporary file
// in ReadWrite Mode
RandomAccessFile tmpraf
= new RandomAccessFile(tmpFile, "rw");
// Set file pointer to start
raf.seek(0);
// Traversing the friendsContact.txt file
while (raf.getFilePointer()
< raf.length()) {
// Reading the contact from the file
nameNumberString = raf.readLine();
index = nameNumberString.indexOf('!');
name = nameNumberString.substring(
0, index);
// Check if the fetched contact
// is the one to be updated
if (name.equals(inputName)) {
// Update the number of this contact
nameNumberString
= name + "!"
+ String.valueOf(newNumber);
}
// Add this contact in the temporary
// file
tmpraf.writeBytes(nameNumberString);
// Add the line separator in the
// temporary file
tmpraf.writeBytes(
System.lineSeparator());
}
// The contact has been updated now
// So copy the updated content from
// the temporary file to original file.
// Set both files pointers to start
raf.seek(0);
tmpraf.seek(0);
// Copy the contents from
// the temporary file to original file.
while (tmpraf.getFilePointer()
< tmpraf.length()) {
raf.writeBytes(tmpraf.readLine());
raf.writeBytes(System.lineSeparator());
}
// Set the length of the original file
// to that of temporary.
raf.setLength(tmpraf.length());
// Closing the resources.
tmpraf.close();
raf.close();
// Deleting the temporary file
tmpFile.delete();
System.out.println(" Friend updated. ");
}
// The contact to be updated
// could not be found
else {
// Closing the resources.
raf.close();
// Print the message
System.out.println(" Input name"
+ " does not exists. ");
}
}
catch (IOException ioe) {
System.out.println(ioe);
}
catch (NumberFormatException nef) {
System.out.println(nef);
}
}
}
// Java program to delete a contact
// from the file "friendsContact.txt"
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.lang.NumberFormatException;
class DeleteFriend {
public static void main(String data[])
{
try {
// Get the name of the contact to be updated
// from the Command line argument
String newName = data[0];
String nameNumberString;
String name;
long number;
int index;
// Using file pointer creating the file.
File file = new File("friendsContact.txt");
if (!file.exists()) {
// Create a new file if not exists.
file.createNewFile();
}
// Opening file in reading and write mode.
RandomAccessFile raf
= new RandomAccessFile(file, "rw");
boolean found = false;
// Checking whether the name of contact exists.
// getFilePointer() give the current offset
// value from start of the file.
while (raf.getFilePointer() < raf.length()) {
// reading line from the file.
nameNumberString = raf.readLine();
// splitting the string to get name and
// number
String[] lineSplit
= nameNumberString.split("!");
// separating name and number.
name = lineSplit[0];
number = Long.parseLong(lineSplit[1]);
// if condition to find existence of record.
if (name == newName) {
found = true;
break;
}
}
// Delete the contact if record exists.
if (found == true) {
// Creating a temporary file
// with file pointer as tmpFile.
File tmpFile = new File("temp.txt");
// Opening this temporary file
// in ReadWrite Mode
RandomAccessFile tmpraf
= new RandomAccessFile(tmpFile, "rw");
// Set file pointer to start
raf.seek(0);
// Traversing the friendsContact.txt file
while (raf.getFilePointer()
< raf.length()) {
// Reading the contact from the file
nameNumberString = raf.readLine();
index = nameNumberString.indexOf('!');
name = nameNumberString.substring(
0, index);
// Check if the fetched contact
// is the one to be deleted
if (name.equals(inputName)) {
// Skip inserting this contact
// into the temporary file
continue;
}
// Add this contact in the temporary
// file
tmpraf.writeBytes(nameNumberString);
// Add the line separator in the
// temporary file
tmpraf.writeBytes(
System.lineSeparator());
}
// The contact has been deleted now
// So copy the updated content from
// the temporary file to original file.
// Set both files pointers to start
raf.seek(0);
tmpraf.seek(0);
// Copy the contents from
// the temporary file to original file.
while (tmpraf.getFilePointer()
< tmpraf.length()) {
raf.writeBytes(tmpraf.readLine());
raf.writeBytes(System.lineSeparator());
}
// Set the length of the original file
// to that of temporary.
raf.setLength(tmpraf.length());
// Closing the resources.
tmpraf.close();
raf.close();
// Deleting the temporary file
tmpFile.delete();
System.out.println(" Friend deleted. ");
}
// The contact to be deleted
// could not be found
else {
// Closing the resources.
raf.close();
// Print the message
System.out.println(" Input name"
+ " does not exists. ");
}
}
catch (IOException ioe) {
System.out.println(ioe);
}
}
}