java实现文件创建读取和打开

功能实例

在这里插入图片描述

主要步骤

文件内容输入代码

Scanner scan=new Scanner(System.in);
String line="";
while(true) {
line=scan.nextLine();
if(line.equals("stop"))
break;
else 
str.append(line+"\n");

其中line为输入的每个字符串模块,每个模块用回车确认,如果该模块不为stop,将其赋值给str全局变量

文件名字和路径创建

filename=new Scanner(System.in).next();
FileWriter filea=new FileWriter(filename);
String str1=str.toString();
filea.write(str1);
filea.flush();
filea.close();

filename为全局变量作为文件名包括路径,其中String str1=str.toString();的作用就是将str(文件内容)转换成Sting类型并赋值给str1,filea.write(str1);filea.flush();filea.close()这三个步骤是必须的,为了写入成功。

打开读取

   String location;
		System.out.print("请输入打开文件的位置:");
		location=new Scanner(System.in).next();
		FileInputStream fos=new FileInputStream(location);
		int data;
		while((data=fos.read())!=-1)
			System.out.print((char)data);
	

实施全部代码

package university;
import java.util.*;
import java.io.*;


public class longlong {
public static StringBuffer str=new StringBuffer();
public static String filename=new String();
public static void main(String[] args) throws IOException{
menushow();
boolean xuze=true;
while(xuze)
{
switch(select())
{
case 1:newfile();break;
case 2:openfile();break;
case 3:savefile();break;
case 0:System.exit(0);break;
default:System.out.println("输入错误");
}
}
}  



public static void newfile() throws IOException{
System.out.println("请输入内容,停止编写请输入stop");
Scanner scan=new Scanner(System.in);
String line="";
while(true) {
line=scan.nextLine();
if(line.equals("stop"))
break;
else 
str.append(line+"\n");

}
}

public static void savefile() throws IOException{
System.out.print("请输入文件胡绝对路径:");
filename=new Scanner(System.in).next();
FileWriter filea=new FileWriter(filename);
String str1=str.toString();
filea.write(str1);
filea.flush();
filea.close();
}


public static void openfile()throws IOException
{    
	   String location;
		System.out.print("请输入打开文件的位置:");
		location=new Scanner(System.in).next();
		FileInputStream fos=new FileInputStream(location);
		int data;
		while((data=fos.read())!=-1)
			System.out.print((char)data);
	


}


public static void menushow() {

System.out.println("******Notepad****************");
System.out.println("*    1.新建文件             *");
System.out.println("*    2.打开文件             *");
System.out.println("*    3.保存文件             *");
System.out.println("*    0.退出                 *");
System.out.println("*****************************");

}

public static int select() {

System.out.print("请输入操作指令:");

int num=new Scanner(System.in).nextInt();

return num;

}

}
  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

超维Ai编程

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

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

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

打赏作者

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

抵扣说明:

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

余额充值