foreword
Hello everyone, this is my overview Vic
today , I hope you like itJava中的读文件,文件的创建,写文件
read file
public static void read(String path,String filename){
try{
int length=0;
String str="";
byte buffer[] = new byte[10];
FileInputStream fis = new FileInputStream(new File(path,filename));
while((length=fis.read(buffer,0,buffer.length))!=-1){
str+=new String(buffer,0,length);
}
System.out.println(str);
fis.close();
}catch(FileNotFoundException e){
System.out.println("文件不存在");
}catch(IOException e){
e.printStackTrace();
}
}
file creation
public class FileDemo{
public static void createFolder(String path){
File folder=new File(path);
if(folder.exists()){
System.out.println("文件夹已存在!");
}else{
folder.mkdir();
}
}
public static void createFile(String path,String filename){
File file=new File(path,filename);
if(file.exists()){
System.out.println("文件已存在!");
System.out.println(file.length());
}else{
try{
file.createNewFile();
}catch(IOException e){
System.out.println("文件创建失败");
}
}
}
public static void main(String[] args){
FileDemo.createFolder("c:/text");
FileDemo.createFile("c:/text","1.txt");
}
}
write file
public static void write(String path,String filename){
try{
String str="123456789";
byte b[] = str.getBytes();
FileOutputStream fos=new FileOutputStream(new File(path,filename));
fos.write(b);
}catch(FileNotFoundException e){
System.out.println("文件不存在");
}catch(IOException e){
System.out.println("写文件失败");
}
}
Get the properties of a file
String getName()
boolean canRead ()
boolean canWrite ()
boolean exits()
boolean isFile()
boolean isDirectory()
boolean isHidden()
Relevant knowledge and technology
boolean mkdir(): create a directory, return true if successful
boolean createNewFile(): create a file
boolean delete(): delete a file
Classification of streams in Java
- The movement direction of the flow: divided into two types: input flow and output flow
- Stream data type: divided into byte stream and character stream
All input stream classes are abstract classes, and all output stream classes are abstract classes.
Bytes: InputStream, OutputStream
Characters: Reader class, Writer class
Read data from the input stream:
FileInputStream vFile=new FileInputStream("File1.dat");
vFile.read();
vFile.close();
output stream:
FileOutputStream oFile=new FileOutputStream("File2.dat");
oFile.write(vFile.read()):
oFile.close();
If you think it's good, then give it a like! ❤️
Summarize
- This article talks about reading files, creating files, and writing files in Java. If you have a better understanding, welcome to communicate
- Positioning: sharing
Android
&Java
knowledge points, if you are interested, you can continue to pay attention