这篇文章主要介绍“Java文件操作的方法”的相关知识,小编通过实际案例向大家展示操作过程,操作方法简单快捷,实用性强,希望这篇“Java文件操作的方法”文章能帮助大家解决问题。
本程序主要采用了FileInputStream和FileOutputStream两类对文件进行操作。具体包括通过相对路径打开文件,三种方法读取文件,查看文件属性,追加文件数据等。
效果图:
完整代码:
package Code.a;
import java.io.*;
public class FileInputStreamDemo {
public static void main(String[] args) {
//获取当前目录;
File f = new File(".");
System.out.print("absolute path:"+f.getAbsolutePath()+"\n");
while(true)
{
try {
//输入命令;
System.out.print("Please input your order:");
BufferedReader stdinBufferedReader;
String str1 = null;
stdinBufferedReader = new BufferedReader(new InputStreamReader(System.in));
str1 = stdinBufferedReader.readLine();
//相对路径打开文件;
File file2 = new File(".\\src\\Code\\a\\Exception.java");
FileInputStream fis2 = new FileInputStream(file2);
根据不同的命令,执行不同操作;
//一次性读取全部数据
if(str1.equals("一次性读取全部数据"))
{
byte[] buf = new byte[(int)(file2.length())];
fis2.read(buf);
String str = new String(buf);
System.out.print(str);
System.out.print("\n");
}
//分块读取
else if(str1.equals("分块读取"))
{
int n = 1024,count;
byte[] buf = new byte[n];
while((count = fis2.read(buf)) != -1)
{
System.out.print(new String(buf,0,count));
}
System.out.print("\n");
}
//逐字读取数据
else if(str1.equals("逐字读取数据"))
{
for(int i = 0; i < file2.length(); i++)
{
char ch = (char)(fis2.read());
System.out.print(ch);
}
System.out.print("\n");
}
//退出
else if(str1.equals("退出"))
{
System.out.print("已退出\n");
break;
}
//查看文件属性
else if(str1.equals("查看文件属性"))
{
System.out.print("If the file or catalog exists:"+file2.exists()+"\n");
System.out.print("If is it a file:"+file2.isFile()+"\n");
System.out.print("If is it a catalog:"+file2.isDirectory()+"\n");
System.out.print("FileName:"+file2.getName()+"\n");
System.out.print("absolute path:"+file2.getAbsolutePath()+"\n");
System.out.print("The last time that the file was changed:"+file2.lastModified()+"\n");
System.out.print("The size of the file:"+file2.length()+" bites\n");
}
//向文件追加数据
else if(str1.equals("文件追加数据"))
{
FileOutputStream fos2 = new FileOutputStream(file2,true);
System.out.println("Please input the content: ");
BufferedReader ContentReader;
String str2 = null;
ContentReader = new BufferedReader(new InputStreamReader(System.in));
str2 = ContentReader.readLine();
fos2.write(str2.getBytes());
fos2.close();
}
//关闭流对象;
fis2.close();
}
//处理异常;
catch(FileNotFoundException fnfe) {
System.out.print("The file open unsuccessfully.");
}catch(IOException ioe) {
ioe.printStackTrace();
}
}
}
}
关于“Java文件操作的方法”的内容就介绍到这里了,感谢大家的阅读。如果想了解更多行业相关的知识,可以关注亿速云行业资讯频道,小编每天都会为大家更新不同的知识点。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。