天天看点

java写入中文乱码的问题解决

今天做一个功能,把输入的log写入到本地,写入后发现里面的中文全部为乱码,查了下资料才发现:

 1.不能直接用 raf.write(String) 方法,而用 raf.write(String.getBytes());

 2.要加上写入模式:

msg.getBytes("UTF-8")
           

全部代码:

public synchronized static void writeLog(String msg){
		if(msg!=null && !msg.equals("")){
			File file =new File(path);
			try {
			        if(!file.exists())
			           file.createNewFile();
				raf = new RandomAccessFile(file, "rw");
				long pos = raf.length();
				raf.seek(pos);
				raf.write(msg.getBytes("UTF-8"));
			    raf.close();
			} catch (FileNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			 }catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}finally{
				
			}
		}
	}