???一次读取一行的操作,在运行时控制台一直在加载,无法输入数据,不知道为啥
1. 创建文件及其文件夹
2. 删除文件及其文件夹
3. 复制文件
4. 重命名文件
5. 读文件
6. 写文件
7. 文件锁
public class OnceFile {//创建文件
public void createFile(String path,String pathName) {
try {
File file = new File(path+File.separator+pathName);
if(!file.exists())
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
//创建文件夹
public void createFileDir(String dir){
File file = new File(dir);
if (!file.exists()){
file.mkdir();
}
}
//删除文件
public void delFile(String pathName){
File file = new File(pathName);
if (file.exists()){
file.delete();
}else {
System.out.println("所删除的文件不存在!");
}
}
//删除某个文件夹及其子文件
public void delFileDir(File file){
File[] filesList = file.listFiles();
for (int i = 0; i < filesList.length; i++) {
if (file.isDirectory()) {
filesList[i].delete();//删除file的子文件及其路径下的文件
}
}
file.delete();
}
//列出文件夹下有哪些文件
public void hasSrc(String path){
File file = new File(path);
File[] filesList = file.listFiles();
System.out.println("--------文件夹下的所有文件及其路径---------");
for (File list:filesList){
System.out.println(list);
}
System.out.println("-------系统跟文件下的文件和路径-------------");
File[] listRoots = file.listRoots();
for (File root:listRoots) {
System.out.println(root);
}
}
//复制文件
//如果找不到原文件则抛出异常
public void copyFile(String fileOldName, String fileNewName){
//创建字节输入流
try (FileInputStream fis = new FileInputStream(fileOldName)) {
//字节输出流
FileOutputStream fos = new FileOutputStream(fileNewName);
byte[] bytes = new byte[1024];
//定义一个实际存储的字节数
int haRead = 0;
//循环读取数据
while ((haRead = fis.read())>0){
//向新的文件写入数据
fos.write(bytes,0,haRead);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
```
//1、重命名文件名,不可更改文件的扩展名,如果该文件不存在,不报错
public void renameFileName(String oldName, String destName){
if(oldName.isEmpty()){
File oldFileName = new File(oldName);
File newFileName = new File(destName);
boolean b = oldFileName.renameTo(newFileName);
if (b){
System.out.println("-------修改成功------");
System.out.println("新的文件名~~~~~"+newFileName.getName());
}
}
}
//2、重命名文件名,不可更改文件的扩展名,如果该文件不存在,不报错
public void renameFile(File oldName, File destName){
if(oldName.exists()){
boolean b = oldName.renameTo(destName);
if (b){
System.out.println("-------修改成功------");
System.out.println("新的文件名~~~~~"+destName.getName());
}
}
}
//读文件
//FileInputStream读文件本身
public void fileInputStreamFile(File file){
try (FileInputStream fis = new FileInputStream(file)) {
byte[] bytes = new byte[1024];
int hasRead = 0;
while ((hasRead = fis.read(bytes))>0){
System.out.println(new String(bytes,0,hasRead));
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
//FileReader读文件本身
public void fileReadFile(File file){
try (FileReader fr = new FileReader(file)) {
//包装成处理流
BufferedReader br = new BufferedReader(fr);
char[] chars = new char[1024];
int hasRead = 0;
while ((hasRead = br.read(chars))>0){
System.out.println(new String(chars,0,hasRead));
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
// 文件读取(内存映射方式).这种方式的效率是最好的,速度也是最快的,因为程序直接操作的是内存
@Test
public void mappedFile(){
File f=new File("E:"+File.separator+"xz"+File.separator+"pom.txt");
byte[] b =new byte[(int) f.length()];;
int len = 0;
try (FileInputStream in = new FileInputStream(f)) {
FileChannel chan = in.getChannel();
MappedByteBuffer buf = chan.map(FileChannel.MapMode.READ_ONLY, 0, f.length());
while (buf.hasRemaining()) {
b[len] = buf.get();
len++;
System.out.println(new String(b,0,len));
}
chan.close();
in.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
//写文件
//FileWriter写文件
public void writeFile(File file){
try (FileWriter fw = new FileWriter(file)) {
fw.write("\t静月思\n\t\t\t--李白\n" );
fw.write("\t窗前明月光\n");
fw.write("\t疑似地上霜\n");
fw.write("\t举头望明月\n");
fw.write("\t低头思故乡\n");
} catch (IOException e) {
e.printStackTrace();
}
}
//PrintWriter写文件本身
public void printWriterFile(File file){
try (FileOutputStream fos = new FileOutputStream(file)) {
PrintStream ps = new PrintStream(file);
ps.print("哈哈哈,笑什么笑,不知道为什么笑");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
/*
RandomAccessFile支持对随机访问文件的读取和写入。
随机访问文件的行为类似存储在文件系统中的一个大型 byte 数组。
存在指向该隐含数组的光标或索引,称为文件指针;输入操作从文件指针开始读取字节,并随着对字节的读取而前移此文件指针。
如果随机访问文件以读取/写入模式创建,则输出操作也可用;输出操作从文件指针开始写入字节,并随着对字节的写入而前移此文件指针。
写入隐含数组的当前末尾之后的输出操作导致该数组扩展。该文件指针可以通过 getFilePointer 方法读取,并通过 seek 方法设置。
*/
//访问指定中间部分的文件数据
public void accessRandomFile(String str,String model,long pos){//model表示以什么形式访问,pos表示记录指针的位置
//创建字节输入流
try (RandomAccessFile raf = new RandomAccessFile(str,model)) {
//移动raf的文件记录指针的位置,定位到pos字节处
raf.seek(pos);
//用来保存实际读取的字节数
int hasRead = 0;
byte[] bytes = new byte[4048];
//循环读取文件中的内容
while ((hasRead = raf.read(bytes))>0){
System.out.println(new String(bytes,0,hasRead));
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
//在指定文件最后追加内容
//model表示以什么形式访问,pos表示记录指针的位置
public void insertContent(File file,String model){
try (RandomAccessFile raf = new RandomAccessFile(file,model)) {
raf.seek(raf.length());
String content = "追加的内容在此,你怕不怕";
//每次追加都会在原来的基础上追加,不会覆盖
raf.write(content.getBytes());
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
//向执行文件、指定位置插入内容的功能
//------原理--------如果需要向指定文件插入内容,程序需要先把插入点后面的内容读入缓冲区,等把需要
//--------------插入的数据写入到文件后,再将缓冲区的内容追加文件后面
///model表示以什么形式访问,pos表示记录指针的位置,insertContent为插入的内容,fileName为文件名
public void insert(String fileName,String model,long pos,String insertContent){
try {
//表示以tmp为后缀的临时文件,null表示默认
File tmp = File.createTempFile("tmp",null);
tmp.deleteOnExit();
//以读写方式来创建文件
RandomAccessFile raf = new RandomAccessFile(fileName,model);
//使用临时文件来保存数据
FileInputStream tmpIn = new FileInputStream(tmp);
FileOutputStream tmpOut = new FileOutputStream(tmp);
raf.seek(pos);
//----------------------下面代码将插入点后的内容读入临时文件中保存------------------
int hasRead = 0;
byte[] bytes = new byte[1024];
//用循环方式读取插入点后的数据
while ((hasRead = raf.read(bytes))>0){
tmpOut.write(bytes,0,hasRead);
}
//-----------------------下面代码用于插入内容---------------------
//把文件指针重新定位到POS位置
raf.seek(pos);
raf.write(insertContent.getBytes());
//追加临时文件中的内容
while ((hasRead = tmpIn.read(bytes)) > 0) {
raf.write(bytes, 0, hasRead);
}
} catch (IOException e) {
e.printStackTrace();
//读取其他进程的输出信息
@Test
public void readFromProcessTest() {
try {
//运行Javac命令,返回该命令的子进程,exec()方法可以运行平台上的其他程序
Process p = Runtime.getRuntime().exec("javac");
//以p进程的错误流创建BufferedReader对象,这个错误对象是本程序的输入流,对p进程则是输出流
BufferedReader br = new BufferedReader(new InputStreamReader(p.getErrorStream()));
String buff = null;
//以循环方式来读取p进程的错误输出
while ((buff = br.readLine()) != null) {
System.out.println(buff.toString());
}
} catch (IOException e) {
e.printStackTrace();
}
}
```
//使用文件锁FileLOck锁定文件
public static void fileLockTest() {
//使用FileOutputStream获取FileChannel
try (FileChannel fileChannel = new FileOutputStream("a.txt").getChannel()) {
System.out.println(fileChannel);
//使用非阻塞方式对指定文件加锁
FileLock lock = fileChannel.tryLock();
//暂停10s
Thread.sleep(10000);
//释放锁
lock.release();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}