Aly Aly - 2 months ago 16
Java Question

Content can not be resolved

While building package in eclipse:

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.StringReader;
import java.io.StringWriter;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import javax.xml.transform.stream.StreamSource;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;
import org.xml.sax.SAXException;

public class JAXBUtil
{
public static String convertJavaToXML(Object object, String pakageName)
throws JAXBException, FileNotFoundException
{
JAXBContext jc = JAXBContext.newInstance(pakageName);

Marshaller m = jc.createMarshaller();

m.setProperty("jaxb.formatted.output", Boolean.TRUE);

StringWriter resultString = new StringWriter();

m.marshal(object, resultString);

return resultString.toString();
}

public static Object convertXMLtoJava(String xml, String pakageName)
throws JAXBException
{
JAXBContext jc = JAXBContext.newInstance(pakageName);

Unmarshaller u = jc.createUnmarshaller();

return u.unmarshal(new StreamSource(new StringReader(xml)));
}

public static Object convertXMLtoJavaWithValidation(String xml, String pakageName, String xsd)
throws JAXBException
{
JAXBContext jc = JAXBContext.newInstance(pakageName);

Unmarshaller u = jc.createUnmarshaller();
try
{
Schema schema = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema").newSchema(new File(xsd));
u.setSchema(schema);
}
catch (SAXException e)
{
e.printStackTrace();
}
return u.unmarshal(new StreamSource(new StringReader(xml)));
}

public static String getContents(File aFile)
{
contents = new StringBuffer();
BufferedReader input = null;
try
{
input = new BufferedReader(new FileReader(aFile));
String line = null;
while ((line = input.readLine()) != null) {
contents.append(line);
}
return contents.toString();
}
catch (FileNotFoundException ex)
{
ex.printStackTrace();
}
catch (IOException ex)
{
ex.printStackTrace();
}
finally
{
try
{
if (input != null) {
input.close();
}
}
catch (IOException ex)
{
ex.printStackTrace();
}
}
}
}


we are getting following three errors:


  • contents can not be resolved (On line number 10)

  • contents can not be resolved (On line number 12)

  • contents can not be resolved to a variable (On line number 3)



We are using Eclipse Neon (4.6.0) and java jdk1.8.0_102

Already tried clean and refresh in Eclipse

Answer

You define contents variable wrong. To define variable in Java you need to start with a type, then variable name and initializing expression (which is optional by the way).

So contents must be defined as follows:

StringBuffer contents = new StringBuffer();

Edit

If you don't need synchronization support you should use StringBuilder class instead of StringBuffer