File Operations In Java

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
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值