30个python使用小技巧(新手如何使用python)
332
2022-08-09
Java文件操作实例详解(java操作ppt)
本文实例为大家分享了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 {
//输入命令;
SystemFgHJTGeP.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 = newFgHJTGeP 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:"+fiFgHJTGePle2.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();
}
}
}
}
版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。
发表评论
暂时没有评论,来抢沙发吧~