⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 writetofile.java

📁 本书属于《开发专家之 Sun ONE》系列丛书
💻 JAVA
字号:
//【代码7-3-5】
//WriteToFile.java
import java.io.*;
class WriteToFile
{
	public static void main(String args[])
	{
		System.out.println("Please enter a directory that the file located in:");
		//构造待读取文件的目录
		StringBuffer stfDir = new StringBuffer();
		//从键盘获取输入字符,存储进入字符缓冲区
		While((char ch = (char)System.in.read())!='\n')
		{
			stfDir.appendChar(ch);
		}
		//创建目录文件对象
		File dir = new File(stfDir.toString());

		System.out.println("Please enter a filename that want to read:");
		//获取待读取的文件名
		StringBuffer stfFilename = new StringBuffer();
		//从键盘获取输入字符,存储进入字符缓冲区
		While((char ch = (char)System.in.read())!='\n')
		{
			stfFilename.appendChar(ch);
		}
		//创建文件对象
		File readFrom = new File(dir,stfFilename.toString());

		//判断文件是否为目录、是否具有写权限、读权限
		if(readFrom.isFile() && reafFrom.canWrite() && reafFrom.canRead())
		{
			//创建RandomAccessFile对象
			RandomAccessFile rafFile = 
new RandomAccessFile(readFrom,"rw");
			//如果未读到文件尾,则继续读取
			int ch;
			StringBuffer stfContent;
			while(ch!=-1)
			{
					//字符缓冲区清空
					stfContent.setLength(0);
					//接收键盘输入、构造字符缓冲区
					while((ch=System.in.read())!=-1)
						stfContent.appendChar(ch);
					//附加Dos格式行结束标志
					stfContent.append("\r\n");
					//将字符缓冲区的内容写出
					rafFile.writeBytes(stfContent.toString());
			}
			//文件关闭
	rafFile.close();
	}
		}
		else
			System.out.println("File cann't be write!");
	}
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -