Windows下创建的txt文件到solaris上用java读取变成乱码,代码如下:
public static String readFileToString(String filePath)
{
File file = new File(filePath);
if(!file.exists())
{
logger.warn("Can not fount file:" + filePath);
return null;
}
try
{
FileInputStream in = new FileInputStream(file);
byte[] b = new byte[in.available()];
in.read(b);
in.close();
return new String(b, StringUtil.getSysEncoding());
}
catch (IOException e)
{
e.printStackTrace();
logger.error("Read file error:" + e.getMessage());
}
return null;
}
StringUtil.getSysEncoding()方法代码如下:/**
* 获得系统编码
* @return
*/
public static String getSysEncoding()
{
return System.getProperty("file.encoding");
}
这是为何???要怎么做才不会乱吗???谢谢
public static String readFileToString(String filePath)
{
File file = new File(filePath);
if(!file.exists())
{
logger.warn("Can not fount file:" + filePath);
return null;
}
try
{
FileInputStream in = new FileInputStream(file);
byte[] b = new byte[in.available()];
in.read(b);
in.close();
return new String(b, StringUtil.getSysEncoding());
}
catch (IOException e)
{
e.printStackTrace();
logger.error("Read file error:" + e.getMessage());
}
return null;
}
StringUtil.getSysEncoding()方法代码如下:/**
* 获得系统编码
* @return
*/
public static String getSysEncoding()
{
return System.getProperty("file.encoding");
}
这是为何???要怎么做才不会乱吗???谢谢
这个地方换成
return new String(b, "GBK");
Windows里面的默认编码格式是GBK,所以你要以GBK的格式构建字符串。