3. 向控制台写输出& 4. PrintWriter类 & 5. 读 写文件

发布于:2025-03-03 ⋅ 阅读:(135) ⋅ 点赞:(0)

4.PrintWriter类


5. 读写文件


对于读写文件,两个最常用的流是FileInputStreamFileOutputStream,这两个类创建与文件链接的字节流。

FileInputStream(String fileName) throws FileNotFoundException;
FileOutputStream(String fileName) throws FileNotFoundException;

文件使用完毕后必须关闭。关闭文件通过close()方法完成。
打开文件并使用int read()方法读取文件中的内容。

package LearnIO;  
  
import java.io.FileInputStream;  
import java.io.FileNotFoundException;  
import java.io.IOException;  
  
/**  
 * 使用read方法  
 *  
 * @author cat  
 * @version 2025/2/27 18:26  
 * @since JDK17  
 */  
public class UseRead01 {  
  
    public static void main(String[] args) {  
        FileInputStream inputStream = null;  
        try {  
            // 打开一个文件  
            inputStream = new FileInputStream("D:\\test.txt");  
            int data;  
            while ((data = inputStream.read()) != -1) {  
                System.out.print(((char) data));  
            }  
        } catch (IOException e) {  
            throw new RuntimeException(e);  
        } finally {  
            try {  
                inputStream.close();    // 使用传统的方法关闭一个文件  
            } catch (IOException e) {  
                throw new RuntimeException(e);  
            }  
        }  
    }  
}
输出 : 
The will of Kowloon is here.

为了向文件写入内容,可使用FileOutputStream定义的write()方法, void write(int byteval) throws IOException
下面程序的功能是将一个文件的内容复制到另一个文件。

package LearnIO;  
  
import java.io.FileInputStream;  
import java.io.FileNotFoundException;  
import java.io.FileOutputStream;  
import java.io.IOException;  
  
/**  
 * 将一个文件的内容复制到另一个文件  
 *  
 * @author cat  
 * @version 2025/2/27 18:37  
 * @since JDK17  
 */  
public class UseWrite {  
    public static void main(String[] args) {  
        FileInputStream inputStream = null;  
        FileOutputStream outputStream = null;  
  
        try {  
            inputStream = new FileInputStream("D:\\test.txt");  
            outputStream = new FileOutputStream("D:\\test02.txt");  
            int data;  
            while ((data = inputStream.read()) != -1) { // 将数据从test.txt中读出  
                outputStream.write(data);               // 将数据写入到test02.txt中  
            }  
        } catch (IOException e) {  
            throw new RuntimeException(e);  
        } finally {  
            try {  
                inputStream.close();  
                outputStream.close();  
            } catch (IOException e) {  
                throw new RuntimeException(e);  
            }  
        }  
    }  
}

网站公告

今日签到

点亮在社区的每一天
去签到