I've hosted a text file which I would like to load into a string using java.
My code doesn't seem to work producing errors, any help?
try {
dictionaryUrl = new URL("http://pluginstudios.co.uk/resources/studios/games/hangman/dictionary.dic");
} catch (MalformedURLException catchMalformedURLException) {
System.err.println("Error 3: Malformed URL exception.\n"
+ " Dictionary failed to load.");
}
// 'Dictionary' scanner setting to file
// 'src/Main/Dictionary.dic'
DictionaryS = new Scanner(new File(dictionaryUrl));
System.out.println("Default dictionary loaded.");
UPDATE 1: The file doesn't seem to load going to the catch. But the file exists.
You could do something that this tutorial does
public class WebPageScanner {
public static void main(String[] args) {
try {
URLConnection connection =
new URL("http://java.net").openConnection();
String text = new Scanner(
connection.getInputStream()).
useDelimiter("\\Z").next();
} catch (IOException e) {
e.printStackTrace();
}
}
}
You need to use HttpClient and retrieve the data as a string or string buffer.
then use parse or read as file.
Something like this should work in your case:
DictionaryS = new Scanner(dictionaryUrl.openStream());
JavaDoc tells us:
File(URI uri)
Creates a new File instance by converting the given file: URI into an abstract pathname.
We can't create and use a File instance for any other resource type (like http).
Related
public void readList () {
try {
FileOutputStream writeData = new FileOutputStream("Accounts.txt");
ObjectOutputStream writeStream = new ObjectOutputStream(writeData);
writeStream.writeObject(AccountCredentials);
writeStream.close();
}
catch (IOException e) {
e.printStackTrace();
}
}
public void writeList() {
try {
FileInputStream readData = new FileInputStream("Accounts.txt");
ObjectInputStream readStream = new ObjectInputStream(readData);
AccountCredentials = (ArrayList <Accounts>) readStream.readObject();
readStream.close();
System.out.println(AccountCredentials.size());
}
catch (Exception e) {
e.printStackTrace();
}
}
My readList method works fine right, I have ¬í sr java.util.ArrayListxÒ™Ça I sizexp w
in the file. My writeList does not. I have a School folder inside the Netbeans folder, and in the main directory is Accounts.txt. Do I need to specify that? My Java file is in Schools/src. It always says my list size is 0
Can you please share the exception or stack trace you are getting and paste it here ? , Also I would highly recommend not to use a flat file for storing the account credentials, rather use any of the identity management solution and db driven account management. Did you also try to debug the following line "ObjectInputStream readStream = new ObjectInputStream(readData);"
I'm trying to upload zip file to the url https://anypoint.mulesoft.com/designcenter/api-designer/projects/{projectId}/branches/master/import. Content-Type must be application/zip, cant change to multipart/form-data. In Mule 3, a java transform class is used (com.test.FileReader) with the FileReader.class is stored in lib. It worked in Mule 3.
I tried to use ReadFile component to read test.zip and set as payload but it's not working. Any suggestion how to upload zip file in Mule 4?
package com.test;
import org.mule.transformer.*;
import org.mule.api.*;
import org.mule.api.transformer.*;
import java.io.*;
public class PayloadFileReader extends AbstractMessageTransformer
{
public Object transformMessage(final MuleMessage message, final String outputEncoding) throws TransformerException {
byte[] result = null;
try {
result = this.readZipFile("test.zip");
}
catch (Exception e) {
e.printStackTrace();
}
message.setPayload((Object)result);
return message;
}
public String readFileTest(final String path) throws FileNotFoundException, IOException, Exception {
final ClassLoader classLoader = this.getClass().getClassLoader();
final File file = new File(classLoader.getResource(path).getFile());
final FileReader fileReader = new FileReader(file);
BufferedReader bufferReader = null;
final StringBuilder stringBuffer = new StringBuilder();
try {
bufferReader = new BufferedReader(fileReader);
String line;
while ((line = bufferReader.readLine()) != null) {
stringBuffer.append(line);
}
}
catch (IOException e) {
e.printStackTrace();
if (bufferReader != null) {
try {
bufferReader.close();
}
catch (IOException e) {
e.printStackTrace();
}
}
}
finally {
if (bufferReader != null) {
try {
bufferReader.close();
}
catch (IOException e2) {
e2.printStackTrace();
}
}
}
return stringBuffer.toString();
}
public byte[] readZipFile(final String path) {
final ClassLoader classLoader = this.getClass().getClassLoader();
final File file = new File(classLoader.getResource(path).getFile());
final byte[] b = new byte[(int)file.length()];
try {
final FileInputStream fileInputStream = new FileInputStream(file);
fileInputStream.read(b);
fileInputStream.close();
}
catch (FileNotFoundException e) {
System.out.println("Not Found.");
e.printStackTrace();
}
catch (IOException e2) {
System.out.println("Error");
e2.printStackTrace();
}
return b;
}
}
'
Assuming that your zip file corresponds to a valid API spec, in Mule 4, you don't need to use a custom java code to achieve what you want: you can read the file content using the File connector Read operation, and use an HTTP Request to upload it to Design Center using Design Center API. Your flow should look like:
For the Read operation, you only need to set the file location, in the File Path operation property.
No need to set content type in the HTTP Request (Mule 4 will configure the content type automatically based on the file content loaded by the Read operation).
You can't use Java code that depends on Mule 3 classes in Mule 4. Don't bother trying to adapt the code, it is not meant to work. Their architecture are just different.
While in Mule 4 you can use plain Java code or create a module with the SDK, there is no reason to do so for this problem and it would be counterproductive. My advise it to forget the Java code and resolve the problem with pure Mule 4 components.
In this case there doesn't seem a need to actually use Java code. The File connector read operation should read the file just fine as it doesn't appear the Java code is doing anything else than reading the file into the payload.
Sending through the HTTP Request connector should be straightforward. You didn't provide any details of the error, (where is it happening, complete error message, HTTP status error code, complete flow with the HTTP request in both versions, etc) and the API Designer REST API doesn't document an import endpoint so it is difficult to say if the request is correctly constructed.
I am passing a file as input stream to parser.parse() method while using apache tika library to convert file to text.The method throws an exception (displayed below) but the input stream is closed in the finally block successfully. Then while renaming the file, the File.renameTo method from java.io returns false. I am not able to rename/move the file despite successfully closing the inputStream. I am afraid another instance of file is created, while parser.parse() method processess the file, which doesn't get closed till the time exception is throw. Is that possible? If so what should I do to rename the file.
The Exception thrown while checking the content type is
java.lang.NoClassDefFoundError: Could not initialize class com.adobe.xmp.impl.XMPMetaParser
at com.adobe.xmp.XMPMetaFactory.parseFromBuffer(XMPMetaFactory.java:160)
at com.adobe.xmp.XMPMetaFactory.parseFromBuffer(XMPMetaFactory.java:144)
at com.drew.metadata.xmp.XmpReader.extract(XmpReader.java:106)
at com.drew.imaging.jpeg.JpegMetadataReader.extractMetadataFromJpegSegmentReader(JpegMetadataReader.java:112)
at com.drew.imaging.jpeg.JpegMetadataReader.readMetadata(JpegMetadataReader.java:71)
at org.apache.tika.parser.image.ImageMetadataExtractor.parseJpeg(ImageMetadataExtractor.java:91)
at org.apache.tika.parser.jpeg.JpegParser.parse(JpegParser.java:56)
at org.apache.tika.parser.CompositeParser.parse(CompositeParser.java:244)
at org.apache.tika.parser.CompositeParser.parse(CompositeParser.java:244)
at org.apache.tika.parser.AutoDetectParser.parse(AutoDetectParser.java:121)
Please suggest any solution. Thanks in advance.
public static void main(String args[])
{
InputStream is = null;
StringWriter writer = new StringWriter();
Metadata metadata = new Metadata();
Parser parser = new AutoDetectParser();
File file = null;
File destination = null;
try
{
file = new File("E:\\New folder\\testFile.pdf");
boolean a = file.exists();
destination = new File("E:\\New folder\\test\\testOutput.pdf");
is = new FileInputStream(file);
parser.parse(is, new WriteOutContentHandler(writer), metadata, new ParseContext()); //EXCEPTION IS THROWN HERE.
String contentType = metadata.get(Metadata.CONTENT_TYPE);
System.out.println(contentType);
}
catch(Exception e1)
{
e1.printStackTrace();
}
catch(Throwable t)
{
t.printStackTrace();
}
finally
{
try
{
if(is!=null)
{
is.close(); //CLOSES THE INPUT STREAM
}
writer.close();
}
catch(Exception e2)
{
e2.printStackTrace();
}
}
boolean x = file.renameTo(destination); //RETURNS FALSE
System.out.println(x);
}
This might be due to other processes are still using the file, like anti-virus program and also it may be a case that any other processes in your application may possessing a lock.
please check that and deal with that, it may solve your problem.
I'm a Java beginner and I need to do the following:
- I have a txt file as input with text that I want to analyse in GATE;
- I want to get GATE to start automatically and run its linguistic analysis (Corpus Pipeline) on this text.
My idea is to open and read the txt file in Java and then convert it to a GATE doc, but I have the following doubts:
1) how do I convert the text to a GATE doc?
2) how do I get GATE to start automatically?
Thanks for helping me out.
In GATE, you don't have to worry about reading and converting common files like .txt, .pdf, .html, etc. GATE automatically does that.
Initialize GATE like this:
private static void initGateApplication(String gateXgappFileLoc, String gateHome) {
try {
try {
if (Gate.getGateHome() == null)
Gate.setGateHome(new File(gateHome));
}
catch (Exception ex) {
ex.printStackTrace(System.out);
}
try {
if (!Gate.isInitialised())
Gate.init();
}
catch (GateException e) {
e.printStackTrace(System.out);
}
System.out.println("Initializing gate application...");
gappFile = new File(gateXgappFileLoc);
gateApplication = (CorpusController) PersistenceManager.loadObjectFromFile(gappFile);
}
catch (Exception e) {
e.printStackTrace(System.out);
}
}
And run your GATE pipeline with your text file:
public void extract(String inputFileName, String docID, CorpusController gateApplication) throws GateException, IOException
{
CorpusController application = gateApplication;
Corpus corpus = Factory.newCorpus("Sample Corpus");
application.setCorpus(corpus);
File docFile = new File(inputFileName);
System.out.print("Processing document " + docFile + "...");
Document doc = Factory.newDocument(docFile.toURL(), encoding);
// add document to the corpus
corpus.add(doc);
// run the application
application.execute();
System.out.println("Done running GATE pipeline...");
// Now use get annotations from 'doc' object
}
I found this code witch I tried and it works great but(!). I want to store the file in a folder that I will choose and also get it from a folder that I again will chose. Since the Sender get an argument then I suppose that if I give an argument like /home/user/test.txt then that's ok and it'll work out fine but I don't get how to store the file to a specific folder ( the Server part in other words ). Any ideas?
If I'm wrong about the argument please by all means correct me :D
PS: It works just fine for the Netbeans' default folder ( no specification of folder for the Sender or Server ).
Any help appreciated.
Frankly speaking, though i feel bad about doing your homework, I am just in a good mood :)
In the below code(FileReciever) i have added a new variable folder which is initalized from the first argument passed to main(). So the name of the folder you want to save the file in mus tbe passed as the first argument. The only other line I have changed is:
File file=new File(folder, file_name);
private String folder = "";
public static void main(String[] args) {
try {
folder = args[0];
ServerSocket listener = new ServerSocket(port);
while (true) {
FileReceiver file_rec = new FileReceiver();
file_rec.socket = listener.accept();
new Thread(file_rec).start();
}
}
catch (java.lang.Exception ex) {
ex.printStackTrace(System.out);
}
}
public void run() {
try {
InputStream in = socket.getInputStream();
int nof_files = ByteStream.toInt(in);
for (int cur_file=0;cur_file < nof_files; cur_file++) {
String file_name = ByteStream.toString(in);
File file=new File(folder, file_name);
ByteStream.toFile(in, file);
}
}
catch (java.lang.Exception ex) {
ex.printStackTrace(System.out);
}
}