「java追加文本」java追加文件内容
本篇文章给大家谈谈java追加文本,以及java追加文件内容对应的知识点,希望对各位有所帮助,不要忘了收藏本站喔。
本文目录一览:
java把控制台输入的文本追加到文本文件中
/**
* 从控制台接收用户输入的数据,并存储在磁盘上
* @param filePath
*/
static void userPrint(String filePath){
BufferedReader br = null;
BufferedWriter bw = null;
try{
//通过System.in返回一个InputStream对象用于构造一个InputStreamReader对象
//再用来构造一个Buffered对象
br = new BufferedReader(new InputStreamReader(System.in));
bw = new BufferedWriter(new FileWriter(filePath,true)); //true表示是否追加
String str = br.readLine(); //接收用户输入
while(!str.equals("exit")){ //如果用户输入exit则退出循环
bw.write(str); //将用户输入的字符串写入文件
bw.newLine(); //换行
bw.flush(); //刷新缓冲区,将缓冲区的字符写入磁盘!
str = br.readLine(); //继续接收输入
}
}
catch(FileNotFoundException e){
System.out.println(e.getMessage());
}
catch(IOException e){
System.out.println(e.getMessage());
}
finally{
try {
bw.close(); //关闭对象前会调用bw.flush();
br.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
java的JTextPane没有append方法,如何追加文本??
java的JtextPane没有append方法,可以使用Document来添加文本,例子如下:
//设置字体大小
SimpleAttributeSet attrset = new SimpleAttributeSet();
StyleConstants.setFontSize(attrset,24);
//插入内容
JTextPane textPane = new JTextPane();
Document docs = textPane.getDocument();//获得文本对象
try {
docs.insertString(docs.getLength(), "要插入的内容", attrset);//对文本进行追加
} catch (BadLocationException e) {
e.printStackTrace();
}
JAVA 对文本文件操作的“追加”
try {
String str = "my information to add\n";//你要添加的信息
RandomAccessFile raf = new RandomAccessFile(new File("D:\\text.txt"),//文件
"rw");
raf.seek(raf.length());//将指针定位到文件最后,即“追加”
raf.writeBytes("\n"+str);
} catch (Exception e) {
e.printStackTrace();
}
关于java追加文本和java追加文件内容的介绍到此就结束了,不知道你从中找到你需要的信息了吗 ?如果你还想了解更多这方面的信息,记得收藏关注本站。