java文件读写操作

常用的文件读写

写文件:

File file = new File("D://test.txt");
		if(!file.exists()){
			file.createNewFile();
		}
		try {
			FileOutputStream out  = new FileOutputStream(file);
			for(int i = 0;i < 5;i++){
				StringBuffer buffer = new StringBuffer();
				buffer.append("这是第"+(i+1)+"行的内容"+"\n");
				out.write(buffer.toString().getBytes());
			}
			out.close();
		} catch (FileNotFoundException e) {
			
			e.printStackTrace();
		}    

  

读文件:

File file = new File("D://test.txt");
		if(!file.exists() || file.isDirectory()){
			System.out.println("file is not exist");
		}
		BufferedReader reader = new BufferedReader(new FileReader(file));
		String temp = "";
		StringBuffer buffer = new StringBuffer();
		temp = reader.readLine();
		while(temp != null){
			buffer.append(temp);
			temp = reader.readLine();
		}
		reader.close();
		System.out.println(buffer);

  

  

posted @ 2017-10-24 10:30  记忆斑驳的回忆  阅读(171)  评论(0编辑  收藏  举报