I am running into following errors while trying to compile a java program on ubbuntu 12.04. . For ease of usage I have put all the classes in the same directory as the java program. I will provide the error message, the main java program as well as the class listing. I deleted the first few comment lines hence the line numbers of the error mesage do not match. I am having problem with the import statements "Scoring Request" and "ScoringResponse"
Also here is the env output
JAVA_HOME=/usr/local/java/jdk1.7.0_10
CLASSPATH=:/home/syedk/WEKA/weka-3-7-9/mysql-connector-java-3.1.17-bin.jar
Error message
=============
javac Scoring.java
Scoring.java:37: error: '.' expected
import ScoringRequest;
^
Scoring.java:37: error: ';' expected
import ScoringRequest;
^
Scoring.java:38: error: class, interface, or enum expected
import ScoringResponse;
^
3 errors
package Scoring;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.StringWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import ScoringRequest;
import ScoringResponse;
#WebServlet( name="Scoring", displayName="Scoring Servlet", urlPatterns = {"/Scoring"}, loadOnStartup=1)
public class Scoring extends HttpServlet {
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
BufferedReader reader = null;
BufferedWriter writer = null;
ScoringRequest req = null;
try {
reader = new BufferedReader(new InputStreamReader(
request.getInputStream()));
StringBuffer xml = new StringBuffer();
String line = reader.readLine();
while (line != null) {
xml.append(line);
line = reader.readLine();
}
req = new ScoringRequest(xml.toString(), null, null,
null);
ScoringResponse res = (new ScoringEngine()).score(req);
writer = new BufferedWriter(new OutputStreamWriter(
response.getOutputStream()));
writer.write(res.toXML());
writer.flush();
} catch (Exception ex) {
System.err.println(ex);
ScoringResponse res = new ScoringResponse(req.getModelName(), req.getPmmlURL(), req.getCsvInputRows(), null);
StringWriter errWriter = new StringWriter();
ex.printStackTrace(new PrintWriter(errWriter));
res.setErrorMessage(errWriter.toString());
// res.setErrorMessage(ex.getMessage());
writer = new BufferedWriter(new OutputStreamWriter(
response.getOutputStream()));
writer.write(res.toXML());
writer.flush();
} finally {
try {
if (reader != null)
reader.close();
} catch (Exception ex) {
}
try {
if (writer != null)
writer.close();
} catch (Exception ex) {
}
}
}
}
These are the problem:
import ScoringRequest;
import ScoringResponse;
You don't import classes from the default package - they're just accessible already. Just remove these two lines and it should be fine - or better, move them into a named package and import them from there. Of course you don't need to import them at all if they're in the same package as the code you're importing in.
As a side note, I would strongly recommend against naming a package the same as a class, as you are doing here:
package Scoring;
...
public class Scoring extends HttpServlet {
...
}
Aside from anything else, Scoring violated the Java conventions for package names.
Related
Let's say I have theese words in a text file
Dictionary.txt
artificial
intelligence
abbreviation
hybrid
hysteresis
illuminance
identity
inaccuracy
impedance
impenetrable
imperfection
impossible
independent
How can I make each word a different object and print them on the console?
You can simple use Scanner.nextLine(); function.
Here is the following code which can help
also import the libraries
import java.util.Scanner;
import java.io.File;
import java.util.Arrays;
Use following code:-
String []words = new String[1];
try{
File file = new File("/path/to/Dictionary.txt");
Scanner scan = new Scanner(file);
int i=0;
while(scan.hasNextLine()){
words[i]=scan.nextLine();
i++;
words = Arrays.copyOf(words,words.legnth+1); // Increasing legnth of array with 1
}
}
catch(Exception e){
System.out.println(e);
}
You must go and research on Scanner class
This is a very simple solution using Files:
package org.kodejava.io;
import java.net.URI;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;
import java.util.Objects;
public class ReadFileAsListDemo {
public static void main(String[] args) {
ReadFileAsListDemo demo = new ReadFileAsListDemo();
demo.readFileAsList();
}
private void readFileAsList() {
String fileName = "Dictionary.txt";
try {
URI uri = Objects.requireNonNull(this.getClass().getResource(fileName)).toURI();
List<String> lines = Files.readAllLines(Paths.get(uri),
Charset.defaultCharset());
for (String line : lines) {
System.out.println(line);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
Source: https://kodejava.org/how-do-i-read-all-lines-from-a-file/
This is another neat solution using buffered reader:
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* BufferedReader and Scanner can be used to read
line by line from any File or
* console in Java.
* This Java program
demonstrate line by line reading using BufferedReader in Java
*
* #author Javin Paul
*/
public class BufferedReaderExample {
public static void main(String args[]) {
//reading file line by line in Java using BufferedReader
FileInputStream fis = null;
BufferedReader reader = null;
try {
fis = new FileInputStream("C:/sample.txt");
reader = new BufferedReader(new InputStreamReader(fis));
System.out.println("Reading
File line by line using BufferedReader");
String line = reader.readLine();
while(line != null){
System.out.println(line);
line = reader.readLine();
}
} catch (FileNotFoundException ex) {
Logger.getLogger(BufferedReaderExample.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(BufferedReaderExample.class.getName()).log(Level.SEVERE, null, ex);
} finally {
try {
reader.close();
fis.close();
} catch (IOException ex) {
Logger.getLogger(BufferedReaderExample.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
Source: https://javarevisited.blogspot.com/2012/07/read-file-line-by-line-java-example-scanner.html#axzz7lrQcYlyy
These are all good answers. The OP didn't state what release of Java they require, but in modern Java I'd just use:
import java.nio.file.*;
public class x {
public static void main(String[] args) throws java.io.IOException {
Files.lines(Path.of("/path/to/Dictionary.txt")).forEach(System.out::println);
}
}
This question already has answers here:
What does a "Cannot find symbol" or "Cannot resolve symbol" error mean?
(18 answers)
Closed 5 years ago.
I have recently started learning about file handling in java. However, in this code (down below), I am trying to close the file at the end of all the reading and writing but am facing an error in doing it this way.
package trycatch;
import java.util.Scanner;
import org.omg.CORBA.DataInputStream;
import java.*;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.Writer;
public class Source {
public static void main(String[] args) throws Exception {
Scanner input = new Scanner(System.in);
try {
File f = new File("record.txt");
FileOutputStream writing = new FileOutputStream(f);
DataOutputStream write = new DataOutputStream(writing);
write.writeUTF("What are the things that you want to do");
String str;
FileInputStream reading = new FileInputStream(f);
java.io.DataInputStream read = new java.io.DataInputStream(reading);
str = read.readUTF();
System.out.println(str);
}
catch(FileNotFoundException e) {
System.out.println("The system collapsed");
}
finally {
write.close(); // write cannot be resolved
read.close(); // read cannot be resolved
}
input.close();
}
}
I am trying out the finally keyword but can you tell me why my IDE cannot recognize read and write when I write it there?
write cannot be resolved
Your read and write fields are local to try block, finally can't access then.Initialize it outside of try.
Try it like that:
package trycatch;
import java.util.Scanner;
import org.omg.CORBA.DataInputStream;
import java.*;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.Writer;
public class Source {
public static void main(String[] args) throws Exception {
Scanner input = new Scanner(System.in);
DataOutputStream write = null;
java.io.DataInputStream read = null;
try {
File f = new File("record.txt");
FileOutputStream writing = new FileOutputStream(f);
write = new DataOutputStream(writing);
write.writeUTF("What are the things that you want to do");
String str;
FileInputStream reading = new FileInputStream(f);
read = new java.io.DataInputStream(reading);
str = read.readUTF();
System.out.println(str);
}
catch(FileNotFoundException e) {
System.out.println("The system collapsed");
}
finally {
if (write != null)
write.close(); // write cannot be resolved
if (read != null)
read.close(); // read cannot be resolved
}
input.close();
}
}
You are declaring write inside the try-block. It can't be resolved inside the finally block as this is a different scope.
You need to declare write before the try-block to make it accessible in finally:
DataOutputStream write = null;
try {
...
write = new DataOutputStream(writing);
...
} finally {
if (write != null) {
write.close();
}
}
With recent versions of Java you could/should use the try-with-resource construct to ensure proper resource handling. With this you can omit the finally-block and the JVM will take care of closing your resources when the try-block is left:
try (DataOutputStream write = new DataOutputStream(writing)) {
...
}
write and read are created in the try block and their scope is only in the block. Move the declaration where you are declaring input and it should work.
I'm learning about servlets in java. Bellow is my code that is suppose to get the content of the url, store it in array list and, display it on the screen. for some reason I'm unable to get the string array content to displayed on the screen. When I load the page I get the "no luck" message. Any ideas why? thanks
//package fortune;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.ArrayList;
import java.util.Random;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import static java.util.Arrays.*;
import java.util.Collections;
import java.util.List;
#WebServlet(name = "FortuneServlet", urlPatterns = {"/"})
public class FortuneServlet extends HttpServlet {
//private String [] cookies = null;
List<String> cookies = new ArrayList<>();
String line ;
public void geturl(String[] args) {
try
{
URL url = new URL(" http://fortunes.cat-v.org/openbsd/");
//URL url = new URL(" http://bbc.com");
// read text returned by server
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
while((line = in.readLine()) != null)
{
cookies.add(line);
//line = in.readLine();
}
in.close();
}
catch (java.net.MalformedURLException e) {
System.out.println("Malformed URL: " + e.getMessage());
}
catch (IOException e) {
System.out.println("I/O Error: " + e.getMessage());
}
}
public void init() throws ServletException {
}
#Override
protected void doGet(
HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
response.setCharacterEncoding("UTF-8");
response.setContentType("text/plain");
if (cookies != null)
{
//response.getWriter().println(
// cookies[new Random().nextInt(cookies.length)]
//);
for (String str: cookies)
{
Collections.shuffle(cookies);
response.getWriter().println(str);
}
}
else {
response.getWriter().println("No luck!");
}
}
}
cookies is always an empty list (unless you are not showing something to us), so you always shuffle it and try to display, but because you don't have anything there you see a blank page.
I would change check cookies != null to !cookies.isEmpty().
EDIT:
You are not adding anything to the cookies list, so it is empty (List<String> cookies = new ArrayList<>();).
Maybe you wanted to call geturl (which does some add on the cookies list) method somewhere in the doGet? Right now it is not used anywhere.
This there anything wrong with my code? I'm new to Java and i'm trying to import a file into MongoDB. However there is a error that i have no idea what is it. I am using Eclipse.
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;
import com.mongodb.Mongo;
import com.mongodb.util.JSON;
import com.mongodb.util.JSONParseException;
public class readwrite {
public static void main(String[] args) throws FileNotFoundException,IOException,JSONParseException{
Mongo mongo = new Mongo("localhost", 27017);
DB db = mongo.getDB("actualdata");
DBCollection collection = db.getCollection("metadata");
String line = null;
StringBuilder sb = new StringBuilder();
try {
FileInputStream fstream = null;
try {
fstream = new FileInputStream("/home/Output/json1-100000-all");
} catch (FileNotFoundException e) {
e.printStackTrace();
System.out.println("File does not exist, exiting");
return;
}
BufferedReader bufferedReader =
new BufferedReader(new InputStreamReader(fstream));
while((line = bufferedReader.readLine()) != null) {
System.out.println(line);
DBObject dbObject;
sb.append(dbObject = (DBObject) JSON.parse(bufferedReader.readLine()));
collection.insert(dbObject);
DBCursor cursorDoc = collection.find();
while (cursorDoc.hasNext()) {
System.out.println(cursorDoc.next());
}
}
bufferedReader.close();
}
catch(FileNotFoundException ex) {
System.out.println("Unable to open file");
}
catch(IOException ex) {
System.out.println(
"Error reading file");
}
}
}
This is the error that is displayed
[
Exception in thread "main" com.mongodb.util.JSONParseException:
{
^
at com.mongodb.util.JSONParser.read(JSON.java:272)
at com.mongodb.util.JSONParser.parseObject(JSON.java:230)
at com.mongodb.util.JSONParser.parse(JSON.java:195)
at com.mongodb.util.JSONParser.parse(JSON.java:145)
at com.mongodb.util.JSON.parse(JSON.java:81)
at com.mongodb.util.JSON.parse(JSON.java:66)
at readwrite.main(readwrite.java:45)
It show me this error when i clicked on at com.mongodb.util.JSONParser.read(JSON.java:272) where it says that the Source is not found. The source attachment does not contain the source for the file JSON.class.
I can print the output of BufferedReader if i did not included the conversion of DBObject. Thanks in advance!
1) Didn't you mean to write JSON.parse(line)
instead of JSON.parse(bufferedReader.readLine())) ?
This might cause it to try and parse 'null' at the last iteration
2) If that doesn't help, could you get the exact string value of 'line' on the failed iteration? (this should be easy using debugger or simple printing to system out)
Regards
Hi, I am totally new in java.
This is my java code:
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.BufferedReader;
public class readw {
public static void main(String[] args) throws IOException {
List<String> lines = new ArrayList<String>();
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader("C:\\run\\input.txt"));
String line = null;
while ((line = reader.readLine()) != null) {
lines.add(line);
}
} finally {
reader.close();
}
String[] array = lines.toArray();
}
}
When I am trying to compile it I got this type of error:
line 8: can not find symbol List (L)and ArrayList(A)
I am trying to get content of my text file and want to set in to as a array.
Add
import java.util.ArrayList;
import java.util.List;
yes its work now i want to see the array result. how?
With
System.out.println(lines);
You need to import all the classes you use.
import java.util.ArrayList;
import java.util.List;