Home Java Javagetting Started What are the commonly used file operations in java?

What are the commonly used file operations in java?

Nov 27, 2020 pm 03:30 PM
java document

What are the commonly used file operations in java?

我们先来介绍一下字节流和字符流的概念及区别:

(学习视频分享:java教学视频

区别字节流和字符流概念

字节流:字节流读取的时候,读到一个字节就返回一个字节;主要用于读取图片,MP3,AVI视频文件。

字符流:字符流使用了字节流读到一个或多个字节,如读取中文时,就会一次读取2个字节。只要是处理纯文本数据,就要优先考虑使用字符流。

字节流和字符流区别

字节流操作的基本单元为字节;字符流操作的基本单元为Unicode码元。字节流默认不使用缓冲区;字符流使用缓冲区。字节流通常用于处理二进制数据,实际上它可以处理任意类型的数据,但它不支持直接写入或读取Unicode码元;字符流通常处理文本数据,它支持写入及读取Unicode码元。

文件常用操作:

创建、删除文件夹

String path = "F:\\test";
File myFile = new File(path);

if (!myFile.exists()) {
    // 创建文件夹
    myFile.mkdir();
    // myFile.mkdirs();

    // 删除文件夹
    myFile.delete();
}

// mkdirs()可以建立多级文件夹, mkdir()只会建立一级的文件夹

创建、删除文件

String content = "Hello World";

// 第一种方法:根据文件路径和文件名
String path = "F:\\test";
String filename = "test.txt";
File myFile = new File(path,filename);

// 第二种方法
String file = "F:\\test\\test.txt";
File myFile = new File(file);

if (!myFile.exists()) {
    // 创建文件(前提是目录已存在,若不在,需新建目录即文件夹)
    myFile.createNewFile();

    // 删除文件
    myFile.delete();
}

写入文件

// 第一种:字节流FileOutputStream
FileOutputStream fop = new FileOutputStream(myFile); 
byte[] contentInBytes = content.getBytes();
fop.write(contentInBytes);  
fop.flush();  
fop.close(); 

// 第二种:FileWriter(参数true为追加内容,若无则是覆盖内容)
FileWriter fw = new FileWriter(myFile,true);
fw.write(content);
fw.close();

// 第三种:BufferedWriter
BufferedWriter bw = new BufferedWriter(new FileWriter(myFile,true));
bw.write(content);  
bw.flush();  
bw.close(); 

// 第四种:打印流PrintStream和PrintWriter
// 字节打印流:PrintStream
// 字符打印流:PrintWriter

PrintWriter pw = new PrintWriter(new FileWriter(myFile,true));   
pw.println(content);      // 换行
pw.print(content);        // 不换行
pw.close();

// 常用BufferedWriter和PrintWriter

读取文件

FileInputStream

// 第一种:以字节为单位读取文件,常用于读二进制文件,如图片、声音、影像等文件。 
InputStream in = new FileInputStream(myFile);

// 一次读一个字节
int tempbyte;  
while ((tempbyte = in.read()) != -1) {  
    System.out.write(tempbyte);  
}  
in.close();

// 一次读多个字节
int byteread = 0;
byte[] tempbytes = new byte[100];
ReadFromFile.showAvailableBytes(in);
while ((byteread = in.read(tempbytes)) != -1) {  
    System.out.write(tempbytes, 0, byteread);  
}  

// System.out.write()方法是字符流,System.out.println()方法是字节流

InputStreamReader

// 第二种:以字符为单位读取文件,常用于读文本,数字等类型的文件 
Reader reader = new InputStreamReader(new FileInputStream(myFile)); 

// 一次读一个字节
int tempchar;  
while ((tempchar = reader.read()) != -1) {  
    // 对于windows下,\r\n这两个字符在一起时,表示一个换行。  
    // 但如果这两个字符分开显示时,会换两次行。  
    // 因此,屏蔽掉\r,或者屏蔽\n。否则,将会多出很多空行。  
    if (((char) tempchar) != '\r') {  
        System.out.print((char) tempchar);  
    }  
}  
reader.close();

// 一次读多个字节
char[] tempchars = new char[30];  
int charread = 0;  
// 读入多个字符到字符数组中,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] == &#39;\r&#39;) {  
                continue;  
            } else {  
                System.out.print(tempchars[i]);  
            }  
        }  
    }  
}

BufferedReader

// 第三种:以行为单位读取文件,常用于读面向行的格式化文件 
BufferedReader reader = new BufferedReader(new FileReader(myFile));
String tempString = null;  
int line = 1;  
// 一次读入一行,直到读入null为文件结束  
while ((tempString = reader.readLine()) != null) {  
    // 显示行号  
    System.out.println("line " + line + ": " + tempString);  
    line++;  
}  
reader.close();  

// 常用BufferedReader

遍历文件(以删除一个文件夹下所有文件为例)

File[] files=myFile.listFiles();   
for(int i=0;i<files.length;i++){   
    if(files[i].isDirectory()){   
        files[i].delete();   
    }   
}

文件函数:

//判断文件是否存在  
myFile.exists()

//读取文件名称  
myFile.getName()

//读取文件路径(相对路径)  
myFile.getPath()

//读取文件绝对路径  
myFile.getAbsolutePath()

//读取文件的父级路径  
new File(myFile.getAbsolutePath()).getParent()

//读取文件的大小  
myFile.length()

//判断文件是否被隐藏  
myFile.isHidden()

//判断文件是否可读  
myFile.canRead()

//判断文件是否可写  
myFile.canWrite()

//判断文件是否为文件夹  
myFile.isDirectory()

相关推荐:java入门教程

The above is the detailed content of What are the commonly used file operations in java?. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

RimWorld Odyssey How to Fish
1 months ago By Jack chen
Can I have two Alipay accounts?
1 months ago By 下次还敢
Beginner's Guide to RimWorld: Odyssey
1 months ago By Jack chen
PHP Variable Scope Explained
3 weeks ago By 百草

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

PHP Tutorial
1506
276
edge pdf viewer not working edge pdf viewer not working Aug 07, 2025 pm 04:36 PM

TestthePDFinanotherapptodetermineiftheissueiswiththefileorEdge.2.Enablethebuilt-inPDFviewerbyturningoff"AlwaysopenPDFfilesexternally"and"DownloadPDFfiles"inEdgesettings.3.Clearbrowsingdataincludingcookiesandcachedfilestoresolveren

Optimizing Nested foreach Loops for Complex Data Structures Optimizing Nested foreach Loops for Complex Data Structures Aug 06, 2025 pm 12:53 PM

To optimize nested foreach loops, redundant iterations should be avoided first, and the time complexity can be reduced from O(n×m) to O(n m); second, if the structure is not truly hierarchical, the data should be flattened using methods such as SelectMany; third, jump out in advance or skip unnecessary processing through conditional judgment; fourth, select appropriate data structures such as dictionary or hash sets to improve search efficiency; fifth, parallelization can be used with caution when operations are independent and time-consuming; sixth, extract complex logic into independent methods or queries to improve readability and maintainability. The core of optimization is to reduce complexity, organize data reasonably, and always evaluate the necessity of nesting, ultimately achieving efficient, clear and extensible code.

Deploying a Java Application to Kubernetes with Docker Deploying a Java Application to Kubernetes with Docker Aug 08, 2025 pm 02:45 PM

Containerized Java application: Create a Dockerfile, use a basic image such as eclipse-temurin:17-jre-alpine, copy the JAR file and define the startup command, build the image through dockerbuild and run locally with dockerrun. 2. Push the image to the container registry: Use dockertag to mark the image and push it to DockerHub and other registries. You must first log in to dockerlogin. 3. Deploy to Kubernetes: Write deployment.yaml to define the Deployment, set the number of replicas, container images and resource restrictions, and write service.yaml to create

How to implement a simple TCP client in Java? How to implement a simple TCP client in Java? Aug 08, 2025 pm 03:56 PM

Importjava.ioandjava.net.SocketforI/Oandsocketcommunication.2.CreateaSocketobjecttoconnecttotheserverusinghostnameandport.3.UsePrintWritertosenddataviaoutputstreamandBufferedReadertoreadserverresponsesfrominputstream.4.Usetry-with-resourcestoautomati

VS Code shortcut to focus on explorer panel VS Code shortcut to focus on explorer panel Aug 08, 2025 am 04:00 AM

In VSCode, you can quickly switch the panel and editing area through shortcut keys. To jump to the left Explorer panel, use Ctrl Shift E (Windows/Linux) or Cmd Shift E (Mac); return to the editing area to use Ctrl ` or Esc or Ctrl 1~9. Compared to mouse operation, keyboard shortcuts are more efficient and do not interrupt the encoding rhythm. Other tips include: Ctrl KCtrl E Focus Search Box, F2 Rename File, Delete File, Enter Open File, Arrow Key Expand/Collapse Folder.

How to execute a prepared statement in Java? How to execute a prepared statement in Java? Aug 06, 2025 pm 04:04 PM

Load the JDBC driver and establish a database connection; 2. Use Connection.prepareStatement() to create a SQL statement containing a placeholder; 3. Call setString(), setInt() and other methods to set parameter values from 1; 4. Call executeUpdate(), executeQuery() or execute() according to the SQL type to execute statements; 5. Use try-with-resources to automatically close the Connection, PreparedStatement and ResultSet resources to prevent memory leaks and ensure safe and efficient processing of database operations.

Solving Common Memory Leaks in Java Applications Solving Common Memory Leaks in Java Applications Aug 06, 2025 am 09:47 AM

Staticfieldsholdingobjectreferencescanpreventgarbagecollection;useWeakHashMaporcleanupmechanisms.2.Unclosedresourceslikestreamsorconnectionscauseleaks;alwaysusetry-with-resources.3.Non-staticinnerclassesretainouterclassreferences;makethemstaticoravoi

How to use Mockito for mocking in Java? How to use Mockito for mocking in Java? Aug 07, 2025 am 06:32 AM

To effectively use Mockito for Java unit testing, you must first add Mockito dependencies, add mockito-core dependencies in the Maven project, and add testImplementation'org.mockito:mockito-core:5.7.0' to the Gradle project; then create mock objects through @Mock annotation (combined with @ExtendWith(MockitoExtension.class)) or mock() method; then use when(...).thenReturn(...) and other methods to stub the method behavior of the mock object, or you can also configure different

See all articles