Could anybody tell me why I'm getting this error, and how to fix the problem?
Exception in thread "main" java.lang.NoClassDefFoundError: org/codehaus/stax2/ri/Stax2ReaderAdapter
at org.codehaus.staxmate.dom.DOMConverter._build(DOMConverter.java:188)
at org.codehaus.staxmate.dom.DOMConverter.buildDocument(DOMConverter.java:171)
at org.codehaus.staxmate.dom.DOMConverter.buildDocument(DOMConverter.java:152)
at org.codehaus.staxmate.dom.DOMConverter.buildDocument(DOMConverter.java:131)
at xmlprocessing.api.STAXModifyCV.main(STAXModifyCV.java:68)
Caused by: java.lang.ClassNotFoundException: org.codehaus.stax2.ri.Stax2ReaderAdapter
at java.net.URLClassLoader$1.run(URLClassLoader.java:202)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:190)
at java.lang.ClassLoader.loadClass(ClassLoader.java:307)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)
at java.lang.ClassLoader.loadClass(ClassLoader.java:248)
... 5 more
Java Result: 1
I wrote the code below:
//-*-*-
FileInputStream input = new FileInputStream("cv.xml");
XMLStreamReader reader = XMLInputFactory.newInstance().createXMLStreamReader(input);
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
//-*-*- get new entries from input stream
System.out.println("<< Sahar CV >>\n -> Modify the first reference\n ** Modify The Name **");
System.out.print(" Enter degree : ");
String degree = in.readLine();
System.out.print(" Enter first name : ");
String fName = in.readLine();
System.out.print(" Enter last name : ");
String lName = in.readLine();
System.out.println(" ** Modify The Address ** ");
System.out.print(" Enter new city : ");
String newCity = in.readLine();
System.out.print(" Enter new country : ");
String newCountry = in.readLine();
//-*-*- let the reader point at the first "reference" element
int eventType;
boolean ref = false, fname = false;
while (!ref && reader.hasNext()) {
eventType = reader.next();
switch (eventType) {
case XMLEvent.START_ELEMENT:
if (reader.getLocalName().equalsIgnoreCase("references")) {
ref = true;
break;
}
}
}
System.out.println("I am here");
//-*-*- start modification
Document doc = new DOMConverter().buildDocument(reader);
Element firstRef = (Element)doc.getElementsByTagName("reference").item(0);
NodeList name = (NodeList)firstRef.getElementsByTagName("name");
//-*-*- modify the degree (Dr. , Eng. , Dev. ,etc)
Attr att = (Attr)name.item(0).getAttributes().item(0);
((Node)att).setNodeValue(degree);
//-*-*- modify first name
NodeList firstName = (NodeList)firstRef.getElementsByTagName("fname");
NodeList firstNameChilds = (NodeList)firstName.item(0).getChildNodes();
((Node)firstNameChilds.item(0)).setNodeValue(fName);
//-*-*- modify last name
NodeList lastName = (NodeList)firstRef.getElementsByTagName("lname");
NodeList lastNameChilds = (NodeList)lastName.item(0).getChildNodes();
((Node)lastNameChilds.item(0)).setNodeValue(lName);
//-*-*- modify city
NodeList city = (NodeList)firstRef.getElementsByTagName("city");
NodeList cityChilds = (NodeList)city.item(0).getChildNodes();
((Node)cityChilds.item(0)).setNodeValue(newCity);
//-*-*- modify country
NodeList country = (NodeList)firstRef.getElementsByTagName("country");
NodeList countryChilds = (NodeList)country.item(0).getChildNodes();
((Node)countryChilds.item(0)).setNodeValue(newCountry);
reader.close();
input.close();
//-*-*- write DOM document
FileOutputStream out = new FileOutputStream("cv.xml");
XMLStreamWriter sw = XMLOutputFactory.newInstance().createXMLStreamWriter(out);
new DOMConverter().writeDocument(doc, sw);
sw.close();
out.close();
You need to make sure the right Woodstox is in your path. Basically, you're using a class that's implemented in that jar, but because the jar isn't in the path Java has no idea what class you're referencing.
This means that a .class file was found that didn't contain the expected class, either because the package doesn't correspond with the directory structure or because the file was renamed after compilation. There are other causes but this is the most common.
Sorry I voted down on the 3 answers but suddenly had a doubt and needed to double check what I thought ... and it ended up being more complex than I thought. However I found a very complete answer for you here:
http://mindprod.com/jgloss/runerrormessages.html#NOCLASSDEFFOUNDERROR
Related
I've written a class for a program designed to help manage a volleyball team's roster. The roster is contained in a .dat file and the players are written as follows:
Rachael Adams 3.36 1.93
My issue arises when I try to separate this string into the proper data types (the name being a string, then the first and second values being doubles for the stats).
public Roster(String filename) {
players = new ArrayList<Player>();
try {
FileReader fr = new FileReader(filename);
BufferedReader inFile = new BufferedReader (fr);
String line = inFile.readLine();
Scanner scan = new Scanner(line);
while(line != null) {
String firstName = scan.next();
String lastName = scan.next();
double attackStat = scan.nextDouble();
double blockStat = scan.nextDouble();
String name = firstName + " " + lastName;
Player newPlayer = new Player(name, attackStat, blockStat);
players.add(newPlayer);
line = inFile.readLine();
}
scan.close();
inFile.close();
} catch (IOException e) {
System.out.println(e);
}
}
The program throws this exception when a Roster object is created
Exception in thread "main" java.util.InputMismatchException
at java.base/java.util.Scanner.throwFor(Scanner.java:939)
at java.base/java.util.Scanner.next(Scanner.java:1594)
at java.base/java.util.Scanner.nextDouble(Scanner.java:2564)
at Roster.<init>(Roster.java:30)
at Assignment08.openRosterFile(Assignment08.java:59)
at Assignment08.main(Assignment08.java:18)
I am newer to Java and still facing a learning curve, so if there is more information needed then please let me know.
If at all possible, I would greatly appreciate an explanation as to what I did wrong rather than just a solution. Thank you very much.
I always find it easier to split the line:
String[] columns = line.split(" (?=\\d)";
String name = columns[0];
double attackStat = Double.parseDouble(columns[1]);
double blockStat = Double.parseDouble(columns[2]);
This works by splitting on a space, but only when the next char is a digit via the look ahead (?=\d).
This automatically caters for any number of words in the name.
Most likely my biggest problem here is not fully understanding Hashmaps and how to manipulate them despite looking at some tutorials. Hopefully you wise souls will be able to point me in the right track.
I'm trying to read a .txt file into a hashmap. The text file contains the popularity of names for 2006. Each line of the inputFile contains a boys name and a girls name as well as how many were named that. For example: 1 Jacob 24,797 Emily 21,365 would be the input from the file for line 1.
I want to put the boys name into one list, and the girls names into a second list maintaining their current positions so that the user can search for jacob and be told it was the number 1 boys name that year, and so on for other names. Previously I was just reading the file line by line and seeing what line the file contained the name i was searching for. This worked, but it was unable to tell if it was a boys name or a girls name, resulting in errors where if I said i was searching for how popular Jacob was for girls, it would still say number 1. I determined a hashmap would be the best way around this, but can't really get it working.
My Code
public void actionPerformed(ActionEvent e)
{
//Parse Input Fields
String name = inputArea.getText();
if (name.equals(""))
{
JOptionPane.showMessageDialog(null, "A name is required.", "Alert", JOptionPane.WARNING_MESSAGE );
return;
}
String genderSelected = genderList.getSelectedItem().toString();
String yearSelected = yearList.getSelectedItem().toString();
String yearFile = "Babynamesranking"+yearSelected+".txt"; //Opens a different name file depending on year selection
boolean foundName = false;
Map<String, String> map = new HashMap<String,String>(); //Creates Hashmap
try
{
File inputFile = new File(yearFile); //Sets input file to whichever file chosen in GUI
FileReader fileReader = new FileReader(inputFile); //Creates a fileReader to open the inputFile
BufferedReader br = new BufferedReader(fileReader); //Creates a buffered reader to read the fileReader
String line;
int lineNum = 1; //Incremental Variable to determine which line the name is found on
while ((line = br.readLine()) != null)
{
if (line.contains(name))
{
outputArea.setText(""+name+" was a popular name during "+yearSelected+".");
outputArea.append("\nIt is the "+lineNum+" most popular choice for "+genderSelected+" names that year.");
foundName = true;
}
String parts[] = line.split("\t");
map.put(parts[0],parts[1]);
lineNum++;
}
fileReader.close();
}
catch(IOException exception)
{
exception.printStackTrace();
}
String position = map.get(name);
System.out.println(position);
}
Sample inputFile:
1 Jacob 24,797 Emily 21,365
2 Michael 22,592 Emma 19,092
3 Joshua 22,269 Madison 18,599
4 Ethan 20,485 Isabella 18,200
5 Matthew 20,285 Ava 16,925
6 Daniel 20,017 Abigail 15,615
7 Andrew 19,686 Olivia 15,474
8 Christopher 19,635 Hannah 14,515
Well, the problem is that by using
if (line.contains(name))
You're checking if the name exists in the whole line, regarding if it's a boy's name or a girl's name. What you can do is to read them separately, then decide which value you want to check. You can do something like this:
while ((line = br.readLine()) != null)
{
Scanner sc = new Scanner(line);
int lineNumber = sc.nextInt();
String boyName = sc.next();
int boyNameFreq = sc.nextInt();
String girlName = sc.next();
int girlNameFreq = sc.nextInt();
if(genderSelected.equals("male") && name.equals(boyName)){
// .. a boy's name is found
}
else if(genderSelected.equals("female") && name.equals(girlName)){
// .. a girl's name is found
}
}
Scanner class is used to parse the line, and read it token-by-token, so you can know if the name is for a boy or girl. Then check on the name that you need only.
You'll want two hashmaps, one for boys' names and one for girls' names - at present you're using boys' names as keys and girls' names as values, which is not what you want. Instead, use two Map<String, IntTuple> data structures where the String is the name and the IntTuple is the line number (rank) and the count of people with this name.
class IntTuple {
final int rank;
final int count;
IntTuple(int rank, int count) {
this.rank = rank;
this.count = count;
}
}
Problem Statement
Write a command line tool which takes a file path as input and prints the number of lines, number of words, number of characters in the file, userid of the owner of the file, groupid of owner of the file and last modification time of the file in UNIX timestamp format. Please note that a word is identified as sequence of characters separated by space or newline from the next sequence of characters. Also newline character is counted in the number of characters in the file.
It has to be written in java.
My code:
try {
File f = new File("src/test.txt");
BufferedReader br = new BufferedReader(new FileReader(f));
String line = br.readLine();
int lines = 0, words = 0, chars = 0;
while (line != null) {
lines++;
for(int i = 0; i < line.length(); i++) {
if(line.charAt(i)==' ') {
words++;
}
}
chars += line.length();
line = br.readLine();
words++;
}
Path path = Paths.get("src/test.txt");
long d2 = Files.getLastModifiedTime(path, LinkOption.NOFOLLOW_LINKS).toMillis();
int uid = (Integer)Files.getAttribute(path, "unix:uid");
System.out.println(lines);
System.out.println(words);
System.out.println(chars);
System.out.println(uid);
System.out.println(uid);
System.out.println(d2);
}
catch(Exception e) {
e.printStackTrace();
}
The problem I am facing is how to find out user id and group id of the owner. I am getting run time error when I used the above code
java.lang.UnsupportedOperationException: View 'unix' not available
at sun.nio.fs.AbstractFileSystemProvider.readAttributes(Unknown Source)
at java.nio.file.Files.readAttributes(Unknown Source)
at java.nio.file.Files.getAttribute(Unknown Source)
at Demo.main(Demo.java:31)
Also after completing my code I would like to submit it but when I submit my code I get a compile time error:
import java.nio.file cannot be resolved
and similarly for others too that belongs to same package, so I would also like to know is there any other method to get these properties where my code gets accepted?
I wrote this simple script that reads a text file and then adds the data to an array however i only want to print the first and last name of the students that have over 90 credits
Student[] student = new Student[50];
Scanner userin, filein;
String filename;
int numStudents;
// Get the filename from the user, with exception handling to deal with incorrect file names
userin = new Scanner(System.in);
filename = null;
filein = null;
filename = Students.txt;
try {
filein = new Scanner(new FileReader(filename)); // try to open the file
} catch (FileNotFoundException e) { // failed to open the file
System.out.println("Invalid file - try again");
filename = null;
}
numStudents = 0;
while (filein.hasNext()){
String lastName = filein.next();
String firstName = filein.next();
double gpa = filein.next();
int Credits = filein.next();
student[numStudents++] = new Student(lastName,firstName,gpa,Credits);
}
int i=0;
do
{
System.out.println(student[i].toString());
i++;
}
while ((student[i] != null)&&(i <= student.length));
"script"?
This is some ugly code. Formatting and structure matter. I'd recommend paying more attention to it in the future. It'll make your maintenance life easier as your programs (aka "scripts") become more complex.
Learn the Sun Java coding standards. You aren't following them now.
Everything in Java has to be a part of a class. I'll assume that you know that. This must be a snippet you cut out of your class.
Your code is too chaotic to worry about making it nice. This'll work:
if (student[i].getCredits() >= 90)
System.out.println(student[i].toString());
I want to read DOM document using Stax stream readers and write it using Stax stream writers.
I want to modify xml file and change some element values
I want the cursor to point at a certain element in xml file befor building dom tree
I wrote this code but the xml file did not modified
can anybody help me ?
FileInputStream input = new FileInputStream("cv.xml");
XMLStreamReader reader = XMLInputFactory.newInstance().createXMLStreamReader(input);
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
//-*-*- get new entries from input stream
System.out.println("<< CV >>\n -> Modify the first reference\n ** Modify The Name **");
System.out.print(" Enter degree : ");
String degree = in.readLine();
System.out.print(" Enter first name : ");
String fName = in.readLine();
System.out.print(" Enter last name : ");
String lName = in.readLine();
System.out.println(" ** Modify The Address ** ");
System.out.print(" Enter new city : ");
String newCity = in.readLine();
System.out.print(" Enter new country : ");
String newCountry = in.readLine();
//-*-*- let the reader point at the first "reference" element
int eventType;
boolean ref = false, fname = false;
while (reader.hasNext()) {
eventType = reader.next();
switch (eventType) {
case XMLEvent.START_ELEMENT:
if (reader.getLocalName().equalsIgnoreCase("references"))
return;
}
}
//-*-*- build DOM trees using Stax stream reader
Document doc = new DOMConverter().buildDocument(reader);
reader.close();
input.close();
//-*-*- start modification
Element firstRef = (Element)doc.getElementsByTagName("reference").item(0);
NodeList name = (NodeList)firstRef.getElementsByTagName("name");
//-*-*- modify the degree (Dr. , Eng. , Dev. ,etc)
Attr att = (Attr)name.item(0).getAttributes().item(0);
((Node)att).setNodeValue(degree);
//-*-*- modify first name
NodeList firstName = (NodeList)firstRef.getElementsByTagName("fname");
NodeList firstNameChilds = (NodeList)firstName.item(0).getChildNodes();
((Node)firstNameChilds.item(0)).setNodeValue(fName);
//-*-*- modify last name
NodeList lastName = (NodeList)firstRef.getElementsByTagName("lname");
NodeList lastNameChilds = (NodeList)lastName.item(0).getChildNodes();
((Node)lastNameChilds.item(0)).setNodeValue(lName);
//-*-*- modify city
NodeList city = (NodeList)firstRef.getElementsByTagName("city");
NodeList cityChilds = (NodeList)city.item(0).getChildNodes();
((Node)cityChilds.item(0)).setNodeValue(newCity);
//-*-*- modify country
NodeList country = (NodeList)firstRef.getElementsByTagName("country");
NodeList countryChilds = (NodeList)country.item(0).getChildNodes();
((Node)countryChilds.item(0)).setNodeValue(newCountry);
//-*-*- write DOM document
FileOutputStream out = new FileOutputStream("cv.xml");
XMLStreamWriter sw = XMLOutputFactory.newInstance().createXMLStreamWriter(out);
new DOMConverter().writeDocument(doc, sw);
sw.close();
out.close();
It's probably because you are returning when you find the "references" element. Maybe break is what you meant.