我有两个类,一个是GUI程序,另一个是索引编写器程序。
GUI程序使用JFileChooser
选择目录并在文本字段中显示它们。
索引编写器应该获取文本字段中的目录并从一个(文档位置)读取并写入另一个(索引位置)。
我想通过点击gui程序中的按钮(indexfbuton)来运行索引编写器程序。
我已经能够在文本字段中显示目录但是当我单击按钮运行索引编写器类时,我会遇到一些错误,请如何解决此问题,谢谢。
这是GUI类:
package upload1;
import upload1.IndexFiles;
import java .awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.io.*;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.LongField;
import org.apache.lucene.document.StringField;
import org.apache.lucene.document.TextField;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig.OpenMode;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.index.Term;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.Date;
public class uploaad extends JFrame implements ActionListener {
private static IndexFiles ind;
public static String uploaad_docsPath;
public static String uploaad_indexPath;
public static void main(String args[]) {
ind = new IndexFiles();
uploaad sfc = new uploaad();
sfc.setVisible(true);
}
public uploaad() {
super("Select File and Keyword");
setSize(350, 200);
setDefaultCloseOperation(EXIT_ON_CLOSE);
Container c = getContentPane();
c.setLayout(new FlowLayout());
final JTextField inputLine = new JTextField();
inputLine.setColumns(22);
JButton openButton = new JButton("Open");
JButton indexButton = new JButton ("Index");
final JButton indexfButton = new JButton("Index Files");
JLabel keyword = new JLabel("Enter Index Destination");
final JTextField inputLine1 = new JTextField();
inputLine1.setColumns(22);
final JLabel statusbar =
new JLabel("Output of your selection will go here");
openButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
JFileChooser chooser = new JFileChooser();
chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
int option = chooser.showOpenDialog(uploaad.this);
if (option == JFileChooser.APPROVE_OPTION) {
File file = chooser.getSelectedFile();
inputLine.setText(file.getAbsolutePath());
uploaad_docsPath = inputLine.getText();
}
else {
statusbar.setText("You canceled.");
}
}
public String uploaad_docsPath(){
return inputLine.getText();}
});
indexButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ap)
{
JFileChooser chooser = new JFileChooser();
chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
int option = chooser.showOpenDialog(uploaad.this);
if (option == JFileChooser.APPROVE_OPTION) {
File file = chooser.getSelectedFile();
inputLine1.setText(file.getAbsolutePath());
uploaad_indexPath = inputLine1.getText();
}
else {
statusbar.setText("You canceled.");
}
}
public String uploaad_indexPath(){
return inputLine.getText();}
});
indexfButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ap)
{
if (ap.getSource().equals( indexfButton) ) {
IndexFiles.index(null);
}
}
});
c.add(indexfButton);
c.add(openButton);
c.add(indexButton);
c.add(inputLine);
c.add(keyword);
c.add(inputLine1);
c.add(statusbar);
}
@Override
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
}
}
这是我想通过按钮事件执行的indexfile类:
package upload1;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.LongField;
import org.apache.lucene.document.StringField;
import org.apache.lucene.document.TextField;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig.OpenMode;
import org.apache.lucene.index.Term;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.index.IndexWriterConfig;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.Date;
import java .awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.io.*;
import java.util.Scanner;
/** Index all text files under a directory.
* <p>
* This is a command-line application demonstrating simple Lucene
* Run it with no command-line arguments for usage information.
*/
public class IndexFiles {
public IndexFiles() {}
public static String uploaad_docsPath;
public static String uploaad_indexPath;
/** Index all text files under a directory. */
public static void index(String[] args) {
String usage = "java org.apache.lucene.demo.IndexFiles"
+ " [-index C:/indexfolder1] [-docs C:/indexfolder] [-
+ "This indexes the documents in C:/indexfolder, creating a
lucene index
+ "in C:/indexfolder1 that can be searched with SearchFiles";
String docsPath;
String indexPath;
docsPath = uploaad.uploaad_docsPath;
indexPath = uploaad.uploaad_indexPath;
// docsPath = inputLine.getText();
// indexPath = inputLine;
boolean create = true;
for(int i=0;i<args.length;i++) {
if ("-index".equals(args[i])) {
indexPath = args[i+1];
i++;
} else if ("-docs".equals(args[i])) {
docsPath = args[i+1];
i++;
} else if ("-update".equals(args[i])) {
create = false;
}
}
if (docsPath == null) {
System.err.println("Usage: " + usage);
System.exit(1);
}
final Path docDir = Paths.get(docsPath);
if (!Files.isReadable(docDir)) {
System.out.println("Document directory '" +docDir.toAbsolutePath()+ "'
does not exist or is not readable, please check the path");
System.exit(1);
}
Date start = new Date();
try {
System.out.println("Indexing to directory '" + indexPath + "'...");
Directory dir = FSDirectory.open(Paths.get(indexPath));
Analyzer analyzer = new StandardAnalyzer();
IndexWriterConfig iwc = new IndexWriterConfig(analyzer);
if (create) {
// Create a new index in the directory, removing any
// previously indexed documents:
iwc.setOpenMode(OpenMode.CREATE);
} else {
// Add new documents to an existing index:
iwc.setOpenMode(OpenMode.CREATE_OR_APPEND);
}
// Optional: for better indexing performance, if you
// are indexing many documents, increase the RAM
// buffer. But if you do this, increase the max heap
// size to the JVM (eg add -Xmx512m or -Xmx1g):
//
// iwc.setRAMBufferSizeMB(256.0);
IndexWriter writer = new IndexWriter(dir, iwc);
indexDocs(writer, docDir);
// NOTE: if you want to maximize search performance,
// you can optionally call forceMerge here. This can be
// a terribly costly operation, so generally it's only
// worth it when your index is relatively static (ie
// you're done adding documents to it):
//
// writer.forceMerge(1);
writer.close();
Date end = new Date();
System.out.println(end.getTime() - start.getTime() + " total
milliseconds");
} catch (IOException e) {
System.out.println(" caught a " + e.getClass() +
"\n with message: " + e.getMessage());
}
}
static void indexDocs(final IndexWriter writer, Path path) throws
IOException {
if (Files.isDirectory(path)) {
Files.walkFileTree(path, new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs)
throws IOException {
try {
indexDoc(writer, file, attrs.lastModifiedTime().toMillis());
} catch (IOException ignore) {
// don't index files that can't be read.
}
return FileVisitResult.CONTINUE;
}
});
} else {
indexDoc(writer, path, Files.getLastModifiedTime(path).toMillis());
}
}
/** Indexes a single document */
static void indexDoc(IndexWriter writer, Path file, long lastModified)
throws IOException {
try (InputStream stream = Files.newInputStream(file)) {
// make a new, empty document
Document doc = new Document();
// Add the path of the file as a field named "path". Use a
// field that is indexed (i.e. searchable), but don't tokenize
// the field into separate words and don't index term frequency
// or positional information:
Field pathField = new StringField("path", file.toString(),
Field.Store.YES);
doc.add(pathField);
// Add the last modified date of the file a field named "modified".
// Use a LongField that is indexed (i.e. efficiently filterable with
// NumericRangeFilter). This indexes to milli-second resolution, which
// is often too fine. You could instead create a number based on
// year/month/day/hour/minutes/seconds, down the resolution you require.
// For example the long value 2011021714 would mean
// February 17, 2011, 2-3 PM.
doc.add(new LongField("modified", lastModified, Field.Store.NO));
// Add the contents of the file to a field named "contents". Specify a
Reader,
// so that the text of the file is tokenized and indexed, but not stored.
// Note that FileReader expects the file to be in UTF-8 encoding.
// If that's not the case searching for special characters will fail.
doc.add(new TextField("contents", new BufferedReader(new
InputStreamReader(stream, StandardCharsets.UTF_8))));
if (writer.getConfig().getOpenMode() == OpenMode.CREATE) {
// New index, so we just add the document (no old document can be
there ):
System.out.println("adding " + file);
writer.addDocument(doc);
} else {
// Existing index (an old copy of this document may have been indexed)
so
// we use updateDocument instead to replace the old one matching the
exact
// path, if present:
System.out.println("updating " + file);
writer.updateDocument(new Term("C:/indexfolder1", file.toString()),
doc);
}
}
}
}
错误消息:
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at upload1.IndexFiles.index(IndexFiles.java:80)
at upload1.uploaad$3.actionPerformed(uploaad.java:141)
at javax.swing.AbstractButton.fireActionPerformed(Unknown Source)
at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.setPressed(Unknown Source)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(Unknown
Source)
at java.awt.Component.processMouseEvent(Unknown Source)
at javax.swing.JComponent.processMouseEvent(Unknown Source)
at java.awt.Component.processEvent(Unknown Source)
at java.awt.Container.processEvent(Unknown Source)
at java.awt.Component.dispatchEventImpl(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Window.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
at java.awt.EventQueue.access$200(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown source)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue.dispatchEvent(Unknown Source)
at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.run(Unknown Source)
答案 0 :(得分:0)
您是否在询问之前阅读了堆栈跟踪? 你不应该在这里传递null作为参数:
public void actionPerformed(ActionEvent ap)
{
if (ap.getSource().equals( indexfButton) ) {
IndexFiles.index(null);
}
}
尝试类似:
public void actionPerformed(ActionEvent ap)
{
if (ap.getSource().equals( indexfButton) ) {
IndexFiles.index(new String[]{});
}
}