Java读写文件

1. Java读写普通文件,以字符串形式读取

private static String fileToJson(String filename){
		BufferedReader reader = null;
		StringBuffer laststr = new StringBuffer();
		try{
			FileInputStream fileInputStream = new FileInputStream(filename);
			InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream, "UTF-8");
			reader = new BufferedReader(inputStreamReader);
			String tempString = null;
			while((tempString = reader.readLine()) != null){
				laststr.append(tempString);
			}
			reader.close();
		}catch(IOException e){
			e.printStackTrace();
		}finally{
			if(reader != null){
				try {
					reader.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return laststr.toString();
	}
2. 读取Properties文件

public static String ReadRara(String ParaName) throws IOException{
		Properties prop = new Properties();// 属性集合对象
		String base = ReadPara.class.getResource("/").getPath();
		FileInputStream fis = new FileInputStream(base + "/para.properties");//属性文件输入流    
		prop.load(fis);// 将属性文件流装载到Properties对象中
		String para = prop.getProperty(ParaName);
		fis.close();// 关闭流
		return para;
	}

3. Java写文件

public static void main(String[] args) {
	FileOutputStream out = null;
	try{
		File file = new File("IMEI.csv");
		out = new FileOutputStream(file);
		OutputStreamWriter osw = new OutputStreamWriter(out, "UTF8");
		BufferedWriter bw = new BufferedWriter(osw);
		for(int i=0;i<count;i++){
			imei = (start+i)+"";
			is_supgsm = (int) (Math.random()*2);
			is_suptd = (int) (Math.random()*2);
			is_supwlan = (int) (Math.random()*2);
			is_p2p = (int) (Math.random()*2); 	
			bw.write(imei + "," + imei_tac + "," + is_supgsm + "," +is_suptd+","+is_supwlan+","+is_p2p+"\n");	        	
		}
		bw.close();
		osw.close();		
	}catch(Exception e){
		e.printStackTrace();
	}finally{
		if(out!=null){
			out.close();
		}
	}
}

4.以append方式写入文件

private static void writeLog() 
	{		
		try{			
			FileWriter writer = new FileWriter("facebook.log", true);//第二个参数表示用append方式写入文件
			writer.append("zhb\n");
			writer.close();	
		}catch(Exception e){
			e.printStackTrace();
		}
	}






评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值