创建一个文件,并从键盘写入数据

创建一个文件,并写入数据

主要是利用File和字节字符流的转换

import java.io.*;
class Test1Demo 
{
	public static void main(String[] args) throws IOException
	{
		String sfilePath = "D:\\Work\\";
		File file = createFile(sfilePath);
		System.out.println("请写入文件内容:");
		writeFile(file);
	}

	public static File createFile(String filePath)
	{
		File file = new File(filePath);
		System.out.println(file.getName());
		if(!file.exists())
		{
			System.out.println(filePath + "路径不存在。");
			return null;
		}
		
		try
		{
			if(file.isDirectory())
			{
				File fileTem = new File(file,"1.txt");
				fileTem.createNewFile();
				return fileTem;
			}
		}
		catch (IOException ex)
		{
			ex.getMessage();
		}
		return null;
	}

	public static void writeFile(File file)
	{
		try
		{
			BufferedReader buffReader = new BufferedReader(new InputStreamReader(System.in));
			BufferedWriter buffWriter = new BufferedWriter(new FileWriter(file));
			String line = null;
			while((line = buffReader.readLine()) != null)
			{
				if("over".equals(line))
					break;
				buffWriter.write(line);
			}

			if(buffReader != null)
				buffReader.close();
			if(buffWriter != null)
				buffWriter.close();
		}
		catch (IOException ex)
		{
			ex.getMessage();
		}
	}
}


你可能感兴趣的:(Java问题专栏)