java创建的文本在什么位置 JAVA 创建一个空文本文档
大家好,关于java创建的文本在什么位置很多朋友都还不太明白,今天小编就来为大家分享关于JAVA 创建一个空文本文档的知识,希望对各位有所帮助!
java生成word文档的问题
Jacob解决Word文档的读写问题收藏
Jacob是Java-COM Bridge的缩写,它在Java与微软的COM组件之间构建一座桥梁。使用Jacob自带的DLL动态链接库,并通过JNI的方式实现了在Java平台上对COM程序的调用。Jacob下载的地址为:
http://sourceforge.net/project/showfiles.php?group_id=109543&package_id=118368
配置:
(1)将解压包中的jacob.dll(x86常用,x64)拷到jdk安装目录下的jre\bin文件夹或windows安装路径下的WINDOWS\system32文件夹下
(2)将jacob.jar文件拷到classpath下即可
常见问题解决:
对于”java.lang.UnsatisfiedLinkError: C:\WINDOWS\system32\jacob-1.14.3-x86.dll:由于应用程序配置不正确,应用程序未能启动。重新安装应用程序可能会纠正”这个问题,可以通过
重新下载Jacob的jar及dll文件(最好版本比现在的低,如1.11)解决
实例制作(主要功能:标题制作,表格制作,合并表格,替换文本,页眉页脚,书签处理):
import com.jacob.activeX.ActiveXComponent;
import com.jacob.com.Dispatch;
import com.jacob.com.Variant;
public class WordOperate{
public static void main(String args[]){
ActiveXComponent wordApp= new ActiveXComponent("Word.Application");//启动word
// Set the visible property as required.
Dispatch.put(wordApp,"Visible", new Variant(true));////设置word可见
Dispatch docs= wordApp.getProperty("Documents").toDispatch();
// String inFile="d:\\test.doc";
// Dispatch doc= Dispatch.invoke(docs,"Open", Dispatch.Method,
// new Object[]{ inFile, new Variant(false), new Variant(false)},//参数3,false:可写,true:只读
// new int[1]).toDispatch();//打开文档
Dispatch document= Dispatch.call(docs,"Add").toDispatch();// create new document
String userName= wordApp.getPropertyAsString("Username");//显示用户信息
System.out.println("用户名:"+ userName);
//文档对齐,字体设置////////////////////////
Dispatch selection= Dispatch.get(wordApp,"Selection").toDispatch();
Dispatch align= Dispatch.get(selection,"ParagraphFormat")
.toDispatch();//行列格式化需要的对象
Dispatch font= Dispatch.get(selection,"Font").toDispatch();//字型格式化需要的对象
//标题处理////////////////////////
Dispatch.put(align,"Alignment","1");// 1:置中 2:靠右 3:靠左
Dispatch.put(font,"Bold","1");//字型租体
Dispatch.put(font,"Color","1,0,0,0");//字型颜色红色
Dispatch.call(selection,"TypeText","Word文档处理");//写入标题内容
Dispatch.call(selection,"TypeParagraph");//空一行段落
Dispatch.put(align,"Alignment","3");// 1:置中 2:靠右 3:靠左
Dispatch.put(selection,"Text","");
Dispatch.call(selection,"MoveDown");//光标标往下一行
//表格处理////////////////////////
Dispatch tables= Dispatch.get(document,"Tables").toDispatch();
Dispatch range= Dispatch.get(selection,"Range").toDispatch();
Dispatch table1= Dispatch.call(tables,"Add", range, new Variant(3),
new Variant(2), new Variant(1)).toDispatch();//设置行数,列数,表格外框宽度
//所有表格
Variant tableAmount= Dispatch.get(tables,"count");
System.out.println(tableAmount);
//要填充的表格
Dispatch t1= Dispatch.call(tables,"Item", new Variant(1))
.toDispatch();
Dispatch t1_row= Dispatch.get(t1,"rows").toDispatch();//所有行
int t1_rowNum= Dispatch.get(t1_row,"count").getInt();
Dispatch.call(Dispatch.get(t1,"columns").toDispatch(),"AutoFit");//自动调整
int t1_colNum= Dispatch.get(Dispatch.get(t1,"columns").toDispatch(),
"count").getInt();
System.out.println(t1_rowNum+""+ t1_colNum);
for(int i= 1; i<= t1_rowNum; i++){
for(int j= 1; j<= t1_colNum; j++){
Dispatch cell= Dispatch.call(t1,"Cell", new Variant(i),
new Variant(j)).toDispatch();//行,列
Dispatch.call(cell,"Select");
Dispatch.put(selection,"Text","cell"+ i+ j);//写入word的内容
Dispatch.put(font,"Bold","0");//字型租体(1:租体 0:取消租体)
Dispatch.put(font,"Color","1,1,1,0");//字型颜色
Dispatch.put(font,"Italic","1");//斜体 1:斜体 0:取消斜体
Dispatch.put(font,"Underline","1");//下划线
Dispatch Range= Dispatch.get(cell,"Range").toDispatch();
String cellContent= Dispatch.get(Range,"Text").toString();
System.out.println((cellContent.substring(0, cellContent
.length()- 1)).trim());
}
Dispatch.call(selection,"MoveDown");//光标往下一行(才不会输入盖过上一输入位置)
}
//合并单元格////////////////////////
Dispatch.put(selection,"Text","");
Dispatch.call(selection,"MoveDown");//光标标往下一行
Dispatch range2= Dispatch.get(selection,"Range").toDispatch();
Dispatch table2= Dispatch.call(tables,"Add", range2, new Variant(8),
new Variant(4), new Variant(1)).toDispatch();//设置行数,列数,表格外框宽度
Dispatch t2= Dispatch.call(tables,"Item", new Variant(2))
.toDispatch();
Dispatch beginCell= Dispatch.call(t2,"Cell", new Variant(1),
new Variant(1)).toDispatch();
Dispatch endCell= Dispatch.call(t2,"Cell", new Variant(4),
new Variant(4)).toDispatch();
Dispatch.call(beginCell,"Merge", endCell);
for(int row= 1; row<= Dispatch.get(
Dispatch.get(t2,"rows").toDispatch(),"count").getInt(); row++){
for(int col= 1; col<= Dispatch.get(
Dispatch.get(t2,"columns").toDispatch(),"count").getInt(); col++){
if(row== 1){
Dispatch cell= Dispatch.call(t2,"Cell", new Variant(1),
new Variant(1)).toDispatch();//行,列
Dispatch.call(cell,"Select");
Dispatch.put(font,"Color","1,1,1,0");//字型颜色
Dispatch.put(selection,"Text","merge Cell!");
} else{
Dispatch cell= Dispatch.call(t2,"Cell", new Variant(row),
new Variant(col)).toDispatch();//行,列
Dispatch.call(cell,"Select");
Dispatch.put(font,"Color","1,1,1,0");//字型颜色
Dispatch.put(selection,"Text","cell"+ row+ col);
}
}
Dispatch.call(selection,"MoveDown");
}
//Dispatch.call(selection,"MoveRight", new Variant(1), new Variant(1));//取消选择
// Object content= Dispatch.get(doc,"Content").toDispatch();
// Word文档内容查找及替换////////////////////////
Dispatch.call(selection,"TypeParagraph");//空一行段落
Dispatch.put(align,"Alignment","3");// 1:置中 2:靠右 3:靠左
Dispatch.put(font,"Color", 0);
Dispatch.put(selection,"Text","欢迎,Hello,world!");
Dispatch.call(selection,"HomeKey", new Variant(6));//移到开头
Dispatch find= Dispatch.call(selection,"Find").toDispatch();//获得Find组件
Dispatch.put(find,"Text","hello");//查找字符串"hello"
Dispatch.put(find,"Forward","True");//向前查找
// Dispatch.put(find,"Format","True");//设置格式
Dispatch.put(find,"MatchCase","false");//大小写匹配
Dispatch.put(find,"MatchWholeWord","True");//全字匹配
Dispatch.call(find,"Execute");//执行查询
Dispatch.put(selection,"Text","你好");//替换为"你好"
//使用方法传入的参数parameter调用word文档中的MyWordMacro宏//
//Dispatch.call(document,macroName,parameter);
//Dispatch.invoke(document,macroName,Dispatch.Method,parameter,new int[1]);
//页眉,页脚处理////////////////////////
Dispatch ActiveWindow= wordApp.getProperty("ActiveWindow")
.toDispatch();
Dispatch ActivePane= Dispatch.get(ActiveWindow,"ActivePane")
.toDispatch();
Dispatch View= Dispatch.get(ActivePane,"View").toDispatch();
Dispatch.put(View,"SeekView","9");//9是设置页眉
Dispatch.put(align,"Alignment","1");//置中
Dispatch.put(selection,"Text","这里是页眉");//初始化时间
Dispatch.put(View,"SeekView","10");// 10是设置页脚
Dispatch.put(align,"Alignment","2");//靠右
Dispatch.put(selection,"Text","这里是页脚");//初始化从1开始
//书签处理(打开文档时处理)////////////////////////
//Dispatch activeDocument= wordApp.getProperty("ActiveDocument").toDispatch();
Dispatch bookMarks= Dispatch.call(document,"Bookmarks").toDispatch();
boolean isExist= Dispatch.call(bookMarks,"Exists","bookMark1")
.getBoolean();
if(isExist== true){
Dispatch rangeItem1= Dispatch.call(bookMarks,"Item","bookMark1")
.toDispatch();
Dispatch range1= Dispatch.call(rangeItem1,"Range").toDispatch();
Dispatch.put(range1,"Text", new Variant("当前是书签1的文本信息!"));
String bookMark1Value= Dispatch.get(range1,"Text").toString();
System.out.println(bookMark1Value);
} else{
System.out.println("当前书签不存在,重新建立!");
Dispatch.call(bookMarks,"Add","bookMark1", selection);
Dispatch rangeItem1= Dispatch.call(bookMarks,"Item","bookMark1")
.toDispatch();
Dispatch range1= Dispatch.call(rangeItem1,"Range").toDispatch();
Dispatch.put(range1,"Text", new Variant("当前是书签1的文本信息!"));
String bookMark1Value= Dispatch.get(range1,"Text").toString();
System.out.println(bookMark1Value);
}
//保存操作////////////////////////
Dispatch.call(document,"SaveAs","D:/wordOperate.doc");
//Dispatch.invoke((Dispatch) doc,"SaveAs", Dispatch.Method, new Object[]{htmlPath, new Variant(8)}, new int[1]);//生成html文件
// 0= wdDoNotSaveChanges
//-1= wdSaveChanges
//-2= wdPromptToSaveChanges
//Dispatch.call(document,"Close", new Variant(0));
//// worddoc.olefunction("protect",2,true,"");
//// Dispatch bookMarks= wordApp.call(docs,"Bookmarks").toDispatch();
//// System.out.println("bookmarks"+bookMarks.getProgramId());
////Dispatch.call(doc,"Save");//保存
//// Dispatch.call(doc,"Close", new Variant(true));
////wordApp.invoke("Quit",new Variant[]{});
// wordApp.safeRelease();//Finalizers call this method
}
}
求基础级java代码,150-200行,自己写的
我有计算器程序
import javax.swing.*;
import javax.swing.border.Border;
import java.awt.*;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.HashMap;
/**
*我的计算器。MyCalculator继承于 JFrame,是计算器的界面
*/
public class Calculator extends JFrame{
/**
*
*/
private static final long serialVersionUID= 1L;
private Border border= BorderFactory.createEmptyBorder(5, 5, 5, 5);
private JTextField textbox= new JTextField("0");
private CalculatorCore core= new CalculatorCore();
private ActionListener listener= new ActionListener(){
public void actionPerformed(ActionEvent e){
JButton b=(JButton) e.getSource();
String label= b.getText();
String result= core.process(label);
textbox.setText(result);
}
};
public Calculator(String title) throws HeadlessException{
super(title);//调用父类构造方法
setupFrame();//调整窗体属性
setupControls();//创建控件
}
private void setupControls(){
setupDisplayPanel();//创建文本面板
setupButtonsPanel();//创建按钮面板
}
//创建按钮面板并添加按钮
private void setupButtonsPanel(){
JPanel panel= new JPanel();
panel.setBorder(border);
panel.setLayout(new GridLayout(4, 5, 3, 3));
createButtons(panel, new String[]{
"7","8","9","+","C",
"4","5","6","-","CE",
"1","2","3","*","",//空字符串表示这个位置没有按钮
"0",".","=","/",""
});
this.add(panel, BorderLayout.CENTER);
}
/**
*在指定的面板上创建按钮
*
*@param panel要创建按钮的面板
*@param labels按钮文字
*/
private void createButtons(JPanel panel, String[] labels){
for(String label: labels){
//如果 label为空,则表示创建一个空面板。否则创建一个按钮。
if(label.equals("")){
panel.add(new JPanel());
} else{
JButton b= new JButton(label);
b.addActionListener(listener);//为按钮添加侦听器
panel.add(b);
}
}
}
//设置显示面板,用一个文本框来作为计算器的显示部分。
private void setupDisplayPanel(){
JPanel panel= new JPanel();
panel.setLayout(new BorderLayout());
panel.setBorder(border);
setupTextbox();
panel.add(textbox, BorderLayout.CENTER);
this.add(panel, BorderLayout.NORTH);
}
//调整文本框
private void setupTextbox(){
textbox.setHorizontalAlignment(JTextField.RIGHT);//文本右对齐
textbox.setEditable(false);//文本框只读
textbox.setBackground(Color.white);//文本框背景色为白色
}
//调整窗体
private void setupFrame(){
this.setDefaultCloseOperation(EXIT_ON_CLOSE);//当窗体关闭时程序结束
this.setLocation(100, 50);//设置窗体显示在桌面上的位置
this.setSize(300, 200);//设置窗体大小
this.setResizable(false);//窗体大小固定
}
//程序入口
public static void main(String[] args) throws Exception{
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
Calculator frame= new Calculator("我的计算器");
frame.setVisible(true);//在桌面上显示窗体
}
}
/**
*计算器核心逻辑。这个逻辑只能处理 1~2个数的运算。
*/
class CalculatorCore{
private String displayText="0";//要显示的文本
boolean reset= true;
int MaxLen= 30;
private BigDecimal number1, number2;
private String operator;
private HashMap<String, Operator> operators= new HashMap<String, Operator>();
private HashMap<String, Processor> processors= new HashMap<String, Processor>();
CalculatorCore(){
setupOperators();
setupProcessors();
}
//为每种命令添加处理方式
private void setupProcessors(){
processors.put("[0-9]", new Processor(){
public void calculate(String command){
numberClicked(command);
}
});
processors.put("\\.", new Processor(){
public void calculate(String command){
dotClicked();
}
});
processors.put("=", new Processor(){
public void calculate(String command){
equalsClicked();
}
});
processors.put("[+\\-*/]", new Processor(){
public void calculate(String command){
operatorClicked(command);
}
});
processors.put("C", new Processor(){
public void calculate(String command){
clearClicked();
}
});
processors.put("CE", new Processor(){
public void calculate(String command){
clearErrorClicked();
}
});
}
//为每种 operator添加处理方式
private void setupOperators(){
operators.put("+", new Operator(){
public BigDecimal process(BigDecimal number1, BigDecimal number2){
return number1.add(number2);
}
});
operators.put("-", new Operator(){
public BigDecimal process(BigDecimal number1, BigDecimal number2){
return number1.subtract(number2);
}
});
operators.put("*", new Operator(){
public BigDecimal process(BigDecimal number1, BigDecimal number2){
return number1.multiply(number2);
}
});
operators.put("/", new Operator(){
public BigDecimal process(BigDecimal number1, BigDecimal number2){
return number1.divide(number2, 30, RoundingMode.HALF_UP);
}
});
}
//根据命令处理。这里的命令实际上就是按钮文本。
public String process(String command){
for(String pattern: processors.keySet()){
if(command.matches(pattern)){
processors.get(pattern).calculate(command);
break;
}
}
return displayText;
}
//当按下 CE时
private void clearErrorClicked(){
if(operator== null){
number1= null;
} else{
number2= null;
}
displayText="0";
reset= true;
}
//当按下 C时,将计算器置为初始状态。
private void clearClicked(){
number1= null;
number2= null;
operator= null;
displayText="0";
reset= true;
}
//当按下=时
private void equalsClicked(){
calculateResult();
number1= null;
number2= null;
operator= null;
reset= true;
}
//计算结果
/**
*
*/
private void calculateResult(){
number2= new BigDecimal(displayText);
Operator oper= operators.get(operator);
if(oper!= null){
try{
BigDecimal result= oper.process(number1, number2);
displayText= result.toString();
} catch(RuntimeException e){
clearClicked();//将计算器置为初始状态
JOptionPane.showMessageDialog(null,"不能用零作除数","出错了",JOptionPane.OK_OPTION);
//e.printStackTrace();
}
}
}
//当按下+-*/时(这里也可以扩展成其他中间操作符)
private void operatorClicked(String command){
if(operator!= null){
calculateResult();
}
number1= new BigDecimal(displayText);
operator= command;
reset= true;
}
//当按下.时
private void dotClicked(){
if(displayText.indexOf(".")==-1){
displayText+=".";
} else if(reset){
displayText="0.";
}
reset= false;
}
//当按下 0-9时
private void numberClicked(String command){
if(reset){
displayText= command;
} else{
if(displayText.length()< MaxLen)
displayText+= command;
else
JOptionPane.showMessageDialog(null,"输入的数字太长了","出错了",JOptionPane.OK_OPTION);
}
reset= false;
}
//运算符处理接口
interface Operator{
BigDecimal process(BigDecimal number1, BigDecimal number2);
}
//按钮处理接口
interface Processor{
void calculate(String command);
}
}
JAVA 创建一个空文本文档
java创建一个文件需要两步:
建立一个路径(Java里File这个名字取得不是很合适,可以把File理解成path)
Filefile=newFile("文件路径");
2.创建文件
file.createNewFile();
例子:在D盘创建一个名为demo.txt的空文本文档
importjava.io.*;
publicclassCreateNewEmptyFile{
publicstaticvoidmain(String[]args){
//在D盘创建一个名为demo.txt的空文本文档
Filefile=newFile("D://demo.txt");
booleanblnCreated=false;
try
{
blnCreated=file.createNewFile();
}
catch(IOExceptionioe)
{
System.out.println("创建文档出现异常:"+ioe);
}
System.out.println("文本文档"+file.getPath()+"是否被创建:"+blnCreated);
}
}
运行结果:运行完成后会在D盘创建一个名为demo.txt的空文本文档
关于java创建的文本在什么位置和JAVA 创建一个空文本文档的介绍到此就结束了,不知道你从中找到你需要的信息了吗 ?如果你还想了解更多这方面的信息,记得收藏关注本站。