Java【File类的使用】输入文件名文件路径及文件名,访问并输出文件中的内容

package demo;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Scanner;

public class Demo1 {

	public static void main(String[] args) {
		boolean isExists = false;
		FileInputStream is = null;
		BufferedInputStream bis = null;
		Scanner sc = new Scanner(System.in);

		while (!isExists) {
			System.out.print("请输入文件路径及文件名:");
			String str1 = sc.next();
			System.out.println(str1);
			String fileName = str1;
			File file = new File(fileName);
			if (file.exists()) {
				int j;
				byte[] buf = new byte[64];
				try {
					is = new FileInputStream(file);
					bis = new BufferedInputStream(is);
					System.out.println("成功打开文件" + file.getName());
					while ((j = bis.read(buf)) != -1) {
						System.out.print(new String(buf, 0, j));
					}

				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} finally {
					try {
						bis.close();
						is.close();
						sc.close();
						isExists = true;
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}

			} else {
				System.out.println("该文件不存在,请重新输入!");
			}
		}

	}

}

在这里插入图片描述
在这里插入图片描述

Java,你可以使用`java.io`包下的如`FileInputStream`, `BufferedReader`读取输入文件内容,再使用`FileOutputStream`和`BufferedWriter`将内容写入输出文件。以下是简单的步骤: 1. **获取用户输入**: 使用`Scanner`获取用户输入文件名,例如: ```java Scanner scanner = new Scanner(System.in); System.out.println("请输入输入文件名:"); String inputFile = scanner.nextLine(); System.out.println("请输入输出文件名:"); String outputFile = scanner.nextLine(); ``` 2. **检查文件是否可访问**: 确保文件路径有效,可以创建`File`对象并检查其是否存在: ```java File inputFileObj = new File(inputFile); File outputFileObj = new File(outputFile); if (!inputFileObj.exists() || !outputFileObj.createNewFile()) { throw new FileNotFoundException("文件无法打开"); } ``` 3. **读取输入文件内容**: 使用`BufferedReader`从输入文件读取数据: ```java try (BufferedReader reader = new BufferedReader(new FileReader(inputFileObj))) { StringBuilder stringBuilder = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { stringBuilder.append(line); } // 将读取的内容保存在stringBuilder里 } catch (IOException e) { e.printStackTrace(); } ``` 4. **写入输出文件**: 使用`BufferedWriter`将`stringBuilder`里的内容写入输出文件: ```java try (BufferedWriter writer = new BufferedWriter(new FileWriter(outputFileObj))) { writer.write(stringBuilder.toString()); } catch (IOException e) { e.printStackTrace(); } ``` 5. **关闭资源**: 最后别忘了关闭`BufferedReader`和`BufferedWriter`。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

爱睡觉的小馨

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值