Error Using HWPFDocument [closed] - java

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 5 years ago.
Improve this question
I have been trying to read a .doc and .docx file and assign the text in the file into a String variable in java but I keep having the error
Exception in thread "main" java.lang.Error: Unresolved compilation problems:
The type org.apache.poi.poifs.filesystem.POIFSFileSystem cannot be resolved. It is indirectly referenced from required .class files
The type org.apache.poi.poifs.filesystem.DirectoryNode cannot be resolved. It is indirectly referenced from required .class files
I have the following code to test the program
import java.io.*;
import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.extractor.WordExtractor;
public class ReadDocFile
{
public static void main(String[] args)
{
File file = null;
WordExtractor extractor = null;
try
{
file = new File("c:\\test.doc");
FileInputStream fis = new FileInputStream(file.getAbsolutePath());
HWPFDocument document = new HWPFDocument(fis);
extractor = new WordExtractor(document);
String[] fileData = extractor.getParagraphText();
for (int i = 0; i < fileData.length; i++)
{
if (fileData[i] != null)
System.out.println(fileData[i]);
}
}
catch (Exception exep)
{
exep.printStackTrace();
}
}
}
I have downloaded a .jar file from
https://mvnrepository.com/artifact/org.apache.poi/poi-scratchpad/3.9
I think the .jar file that I imported is incomplete. If so, can anyone give me a link for the complete library?

You need to include poi-3.15.jar into your classpath.
You can find all poi jars & dependencies as single download here
If you are using maven,
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.15</version>
</dependency>

Related

Get something like Resultset from data file [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 7 years ago.
Improve this question
I want to read a delimiter-separated or fixed-width file (of defined layout), and want to get something like a Resultset through which I can iterate throgh the record.
Is there any reliable library for doing this? If not then can anyone please suggest me how I should proceed? An example code snippet will be very helpful to me.
You can use java ios to iterate each line in the text file and then implement your own logic to split the line and do as desired.
public static void main(String args[]) throws Exception {
//input file
File inputFile = new File("c:/hadoop/sample.txt");
BufferedReader br = new BufferedReader(new FileReader(inputFile));
String s = null;
while ((s = (br.readLine())) != null) {
//check each line and do the logic may be split or based on the requirement
String cols[] =s.split("|");
}
}
public static Stream<String> lines(Path path)
throws IOException
Read all lines from a file as a Stream. Bytes from the file are decoded into characters using the UTF-8 charset.
This method works as if invoking it were equivalent to evaluating the expression:
Files.lines(path, StandardCharsets.UTF_8)
Parameters:
path - the path to the file
Returns: the lines from the file as a Stream
Throws:
IOException - if an I/O error occurs opening the file
SecurityException - In the case of the default provider, and a security manager is installed, the checkRead method is invoked to check read access to the file.
Since: 1.8
Files.lines(Path) expects a Path argument and returns a Stream<String>.
This is Java 8, so you can use lambda expressions or method references to provide a Consumer argument.
public class FixedWidthFile {
public static void main(String JavaLatte[]) {
Path path = Paths.get("/home/sample.txt");
try {
Stream<String> lines = Files.lines(path);
lines.forEach(s -> System.out.println(s));
} catch (IOException ex) {
}
}
}
Reference: Class Files

Java File file = new file not working ; cannot find symbol [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
At the moment I'm making a HangMan GUI game in Java. It works when I put the words right into the program.
But now I want to load a textfile and create a string of it, in the code below the string content.
Here on StackOverflow I have read about the use of scanners.
Now I have this code, but it won't accept the File file = new File("woordenlijst.txt"); statement, it says at 'File' that it cannot find symbol. Can you help me? this is my code:
import java.util.Scanner;
public class galgjeGUI extends javax.swing.JFrame {
/**
* Creates new form galgjeGUI
*/
private String wGalg; // het te raden woord
private int fouten; // globale variabele toegevoegd jonp
private int pogingen;
private int levens = 7;
public galgjeGUI() {
initComponents();
buttonDisableFunction();
File file = new File("woordenlijst.txt");
Scanner scan = new Scanner(file);
scan.useDelimiter("\\Z");
String content = scan.next();
}
how does java know what you mean by File, there is no class called File, you are looking for java.io.File so tell compiler to use that by adding
import java.io.File;
1) Import proper packages.
2) Handle exceptions.
3) close() Scanner object after usage.
import java.io.*; //import
Scanner scan = null;
try { //handle exceptions
File file = new File("woordenlijst.txt");
scan = new Scanner(file);
}
catch(FileNotFoundException e) {
System.out.println(e);
}
finally {
scan.close(); // give up the resource.
}

Cant find file in the raw folder in android [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 9 years ago.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Improve this question
I have a file dictionary.txt and I need to get that file from the raw folder so I googled around and found this:
Here's an example:
"android.resource:///"+getPackageName()+ "/" + R.raw.dictionary;
but it did not work, Any idea?
Edit:
here is what i am doing
for(String line: FileUtils.readLines(file))
{
if(line.toLowerCase().equals(b.toLowerCase()))
{
valid = true;
}
}
You can get an input stream on a raw resource by using:
getResources().openRawResource(R.raw.dictionary);
EDIT:
From your edit, there really isn't a reason as to why you would specifically need the file rather than just using the input stream available from the openRawResource(int id) method...just use an existing java class http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html#Scanner%28java.io.InputStream,%20java.lang.String%29.
Scanner scanner = new Scanner(getResources().openRawResource(R.raw.dictionary));
while(scanner.hasNextLine()){
{
if(scanner.nextLine().toLowerCase().equals(b.toLowerCase()))
{
valid = true;
}
}
}
Unfortunately you can not create a File object directly from the raw folder. You need to copy it in your sdcard or inside the application`s cache.
you can retrieve the InputStream for your file this way
InputStream in = getResources().openRawResource(R.raw.yourfile);
try {
int count = 0;
byte[] bytes = new byte[32768];
StringBuilder builder = new StringBuilder();
while ( (count = is.read(bytes,0 32768) > 0) {
builder.append(new String(bytes, 0, count);
}
is.close();
reqEntity.addPart(new FormBodyPart("file", new StringBody(builder.toString())));
} catch (IOException e) {
e.printStackTrace();
}
EDIT:
to copy it over to internal storage:
File file = new File(this.getFilesDir() + File.separator + "fileName.ext");
try {
InputStream inputStream = resources.openRawResource(R.id._your_id);
FileOutputStream fileOutputStream = new FileOutputStream(file);
byte buf[]=new byte[1024];
int len;
while((len=inputStream.read(buf))>0) {
fileOutputStream.write(buf,0,len);
}
fileOutputStream.close();
inputStream.close();
} catch (IOException e1) {}
Now you have a File that you can access anywhere you need it.
Place the file in the assets folder and open it like this
getResources().getAssets().open("dictionary.txt");

How to write data to a text file in Java [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I'm creating a sport prediction game for my Grade 11 year and I'm having issues writing data to a text file. I'm using NetBeans 7.3.1. I'm using a button where every time it is pressed data entered by the user must be written to the text file. The text file is empty in the beginning and I need to add data to it. After the first click on the button the data keep rewriting itself and the new data is not added. It needs to be in a new line each time. Thank you very much. Some coding would be awesome!
I just did a quick search for appending to a file (usually a good thing to do): this question seems to be what your looking for.
I haven't tested this, but this should work:
private boolean appendToFile(String fileName, String data, String lineSeparator)
throws IOException {
FileWriter writer = null;
File file = new File(fileName)
if (!file.exists()) {
file.createNewFile();
}
try {
writer = new FileWriter(fileName, true);
writer.append(data);
writer.append(lineSeparator);
} catch (IOException ioe) {
return false;
} finally {
if (writer != null) {
writer.close();
}
}
return true;
}

Quickest way to convert XML to JSON in Java [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 7 years ago.
Improve this question
What are some good tools for quickly and easily converting XML to JSON in Java?
JSON in Java has some great resources.
Maven dependency:
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20180813</version>
</dependency>
XML.java is the class you're looking for:
import org.json.JSONObject;
import org.json.XML;
import org.json.JSONException;
public class Main {
public static int PRETTY_PRINT_INDENT_FACTOR = 4;
public static String TEST_XML_STRING =
"<?xml version=\"1.0\" ?><test attrib=\"moretest\">Turn this to JSON</test>";
public static void main(String[] args) {
try {
JSONObject xmlJSONObj = XML.toJSONObject(TEST_XML_STRING);
String jsonPrettyPrintString = xmlJSONObj.toString(PRETTY_PRINT_INDENT_FACTOR);
System.out.println(jsonPrettyPrintString);
} catch (JSONException je) {
System.out.println(je.toString());
}
}
}
Output is:
{"test": {
"attrib": "moretest",
"content": "Turn this to JSON"
}}
To convert XML File in to JSON include the following dependency
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20140107</version>
</dependency>
and you can Download Jar from Maven Repository here.
Then implement as:
String soapmessageString = "<xml>yourStringURLorFILE</xml>";
JSONObject soapDatainJsonObject = XML.toJSONObject(soapmessageString);
System.out.println(soapDatainJsonObject);
The only problem with JSON in Java is that if your XML has a single child, but is an array, it will convert it to an object instead of an array. This can cause problems if you dynamically always convert from XML to JSON, where if your example XML has only one element, you return an object, but if it has 2+, you return an array, which can cause parsing issues for people using the JSON.
Infoscoop's XML2JSON class has a way of tagging elements that are arrays before doing the conversion, so that arrays can be properly mapped, even if there is only one child in the XML.
Here is an example of using it (in a slightly different language, but you can also see how arrays is used from the nodelist2json() method of the XML2JSON link).
I found this the quick and easy way:
Used: org.json.XML class from java-json.jar
if (statusCode == 200 && inputStream != null) {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
StringBuilder responseStrBuilder = new StringBuilder();
String inputStr;
while ((inputStr = bufferedReader.readLine()) != null) {
responseStrBuilder.append(inputStr);
}
jsonObject = XML.toJSONObject(responseStrBuilder.toString());
}
I have uploaded the project you can directly open in eclipse and run
that's all
https://github.com/pareshmutha/XMLToJsonConverterUsingJAVA
Thank You
I don't know what your exact problem is, but if you're receiving XML and want to return JSON (or something) you could also look at JAX-B. This is a standard for marshalling/unmarshalling Java POJO's to XML and/or Json. There are multiple libraries that implement JAX-B, for example Apache's CXF.

Categories