怎样将textarea中的内容写入文件,特别是换行的问题。
多谢~~~
多谢~~~
解决方案 »
- spring 上下文 获取的问题
- 请问java的子类如何重载父类的方法?
- 难!!急!!!!一个关于jquery的问题,请求帮助!!!!!!!!!!!!!!!!!!!
- webservices针对xml某个节点下的参数进行加密怎么来做?
- 求助 SWT 的browser组件 如何处理当前页面的超链接?
- 方法的参数用Class对象有什么好处?
- 我写一个bat来运行我的程序,可是运行完以后,cmd窗口就会自动关闭,请问如何使程序运行完,控制台窗口也不关闭?谢谢
- 请问Java开发的程序能否与MicroSoft的消息队列(MSMQ)之间实现相互通信
- java绘图问题
- 会用intellij_idea请进。。。。。。。
- System.currentTimeMillis() 得到的毫秒时间是以1毫秒为单位,还是以10毫秒为单位
- JCeator 没有设置断点的地方?? 有谁用过这东东....(马上结贴)
楼主【aaronhanfei】截止到2008-07-03 16:37:04的历史汇总数据(不包括此帖):
发帖的总数量:6 发帖的总分数:270
结贴的总数量:6 结贴的总分数:270
无满意结贴数:1 无满意结贴分:20
未结的帖子数:0 未结的总分数:0
结贴的百分比:100.00% 结分的百分比:100.00%
无满意结贴率:16.67 % 无满意结分率:7.41 %
敬礼!
/**
* 在页面上直接显示文本内容,替换小于号,空格,回车,TAB
*
* @param str String 原始字符串
* @return String 替换后的字符串
*/
public static String htmlshow(String str) {
if (str == null) {
return null;
} str = replace("<", "<", str);
str = replace(" ", " ", str);
str = replace("\r\n", _BR, str);
str = replace("\n", _BR, str);
str = replace("\t", " ", str);
return str;
}
/**
* 写至文件
* @param file 文件对象
* @param text JTextArea对象
*/
public void writeFile(File file, JTextArea text)
{
String str = formatLineSeparator(text.getText(), "\n", System.getProperty("line.separator"));
FileOutputStream outFile = null;
FileChannel channel = null;
final byte[] bt = str.getBytes();
ByteBuffer buf = null; try
{
outFile = new FileOutputStream(file);
channel = outFile.getChannel();
int size = bt.length / 1024;
int mod = bt.length % 1024;
int start = 0;
int end = 0;
for(int i = 0; i < size + 1; i++)
{
if(i == size)
{
if(mod > 0)
{
buf = ByteBuffer.allocate(mod);
start = end;
end += mod;
}
else
{
break;
}
}
else
{
buf = ByteBuffer.allocate(1024);
start = end;
end = (i + 1) * 1024;
}
for(byte b: getSubBytes(bt, start, end))
{
buf.put(b);
} buf.flip();
channel.write(buf);
}
}
catch(Exception e)
{
e.printStackTrace();
}
finally
{
try
{
channel.close();
outFile.close();
}
catch(Exception e)
{}
}
}
/**
* 获取一字节数组的一子数组
* @param bt 基准字节数组
* @param start 开始位置
* @param end 结束位置
* @return 子字节数组
*/
private byte[] getSubBytes(byte[] bt, int start, int end)
{
int size = end - start;
byte[] result = new byte[size];
for(int i = 0; i < size; i++)
{
result[i] = bt[i + start];
}
return result;
}
/**
* 格式化换行符
* @param str 文本
* @param oldLineSep 旧的换行符
* @param newLineSep 新的换行符
* @return 格式化后的文本
*/
private String formatLineSeparator(String str, String oldLineSep, String newLineSep)
{
StringBuffer sb = new StringBuffer(str);
int length = oldLineSep.length();
long index = -1;
String tempStr = str;
while((index = tempStr.lastIndexOf(oldLineSep)) >= 0)
{
tempStr = tempStr.substring(0, (int)index);
sb.delete((int)index, (int)(index + length));
sb.insert((int)index, newLineSep);
}
return sb.toString();
}