File Operations In Java

2015/08/27 13:20
阅读数 14

The “File” class in Java defines many useful methods, here is a program which demonstrates some of these methods.

 
import java.io.*;
 
public class streams
{
	public static void main(String []args)
	{
		File f1=new File("Folder/FILE");
		File f2=new File("Folder/FILE1");
 
		String s;
 
		if(f1.exists())
		{
			if(f1.isFile())
			{
				System.out.println("File Name is "+f1.getName());
				s=f1.getParent();
 
				File f3=new File(s);
 
				f1.renameTo(new File("Folder/abc"));
 
				f2.delete();
 
				if (f3.isDirectory())
				{
					System.out.println(f2.getPath());
				}
			}
			else
			{
				System.out.println("Not a File");
			}
		}
	}
}
The output of the program is:
 
File Name is FILE
Folder

If successfully run , the ” FILE ” file inside the folder ” Folder ” will be renamed to ” abc ” and the ” FILE1 ” file will be deleted.

Here is an example of a program that reads its own first six bytes, we have:

 
//0123
 
import java.io.*;
 
public class read
{
	public static void main(String []args)
	{
		int s=6;
		int b[]=new int[6];
		char c[]=new char[6];
		try
		{
			FileInputStream f = new FileInputStream("read.java");
 
			for (int i=0; i<6; i++)
			{
				b[i] = f.read();
				c[i] = (char) b[i];
			}
 
			System.out.println("First 6 bytes of the file are :");
			for (int i=0;i<6;i++)
				System.out.print(b[i]+" ");
 
			System.out.println("nnFirst 6 Bytes as characters  :");
			for (int i=0;i<6;i++)
				System.out.print(c[i]);
		}
		catch (Exception e)
		{
			System.out.println("Error");
		}
	}
}
 
This program produces the following output:
 
First 6 bytes of the file are :
47 47 48 49 50 51
 
First 6 Bytes as characters are :
 
//0123

Notice that the FileInputStream object is created inside a try-catch block since if the specified-file does not exist, an exception is raised.

In the same way to write data to a file byte-by-byte, we have:

 
import java.io.*;
 
public class witer
{
	public static void main(String []args) throws IOException
	{
		String s="Hello";
 
		byte b[]=s.getBytes();
 
		FileOutputStream f=new FileOutputStream("file.txt");
 
		int i=0;
		while(i
		{
			f.write(b[i]);
			i++;
		}
	}
}

If the file called file.txt does not exist, it is automatically created.

If we place a true in the constructor for the FileOutputStream, then the file would be opened in append mode.
Note: All file paths used here are relative paths , Use absolute path or add the relative path to the classpath, Copy the folders to the bin folder

版权声明:本文为博主原创文章,未经博主允许不得转载。

展开阅读全文
打赏
0
0 收藏
分享
加载中
更多评论
打赏
0 评论
0 收藏
0
分享
返回顶部
顶部