What Does "file does not contain class api.configuration" Mean? - java

Please keep in mind that I am completely new to Java. I don't know what 'classes' and stuff are.
When trying to compile (javac -g Sphinx.java) this code:
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.PrintWriter;
import api.Configuration;
import api.SpeechResult;
import api.LiveSpeechRecognizer;
public class Sphinx {
public static void main(String[] args) throws Exception {
Configuration configuration = new Configuration();
configuration.setAcousticModelPath("models/en-us/en-us");
configuration.setDictionaryPath("models/en-us/cmudict-en-us.dict");
configuration.setLanguageModelPath("models/en-us/en-us.lm.bin");
PrintWriter pw = new PrintWriter(new PrintWriter("status.txt"));
LiveSpeechRecognizer recognizer = new LiveSpeechRecognizer(configuration);
recognizer.startRecognition(true);
pw.print("running");
SpeechResult result = recognizer.getResult();
recognizer.stopRecognition();
pw.print("stopped");
pw.close();
PrintWriter pw2 = new PrintWriter(new PrintWriter("result.txt"));
pw2.println(result);
pw2.close();
}
}
I get this error:
Sphinx.java:8: error: cannot access Configuration
import api.Configuration;
^
bad source file: .\api\Configuration.java
file does not contain class api.Configuration
Please remove or make sure it appears in the correct subdirectory of the sourcepath.
I don't quite understand what 'file does not contain class api.configuration' means, or how to fix it.

Looking at your error message, it seems like your ./api/Configuration.java file is missing a package declaration.
Can you make sure that in ./api/Configuration.java the first line has
package api;
This tells the compiler that your file is accessible through the api package, not the default package.

Related

How to write files in different directories based on different spring-profiles?

I generate a Zip File in my code and now i want to weite it in a directory
/export
in Production then I want to write it in
/foo/bar
I already got 2 Profiles (it & Production):
application-it.yaml
application-production.yaml
But how do I manage two save locations in my code now or what propertie should I use for that?
In Spring Boot you can do it like this.
'application-it.yml' content:
file.storage: "/export"
'application-production.yml' content:
file.storage: "/foo/bar"
I don't know your real implementation. But imagine that you use service to process the file. Then you can include #Value to your service to include specific variable.
My 'SimpleService.java' content:
package test.service;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
#Service
public class SimpleService {
private static final Logger LOG = LoggerFactory.getLogger(SimpleService.class);
#Value("${file.storage}")
private String fileStorage;
public void saveFile() throws IOException {
LOG.info("Folder to store files: {}", fileStorage);
File file = new File(fileStorage + File.separatorChar + "test.zip");
ZipOutputStream outputStream = new ZipOutputStream(new FileOutputStream(file));
ZipEntry entry = new ZipEntry("entry.txt");
outputStream.putNextEntry(entry);
outputStream.write("test".getBytes());
outputStream.closeEntry();
outputStream.close();
}
}
And finally, when you start your app (in my case with Maven) specify active app profile:
-Dspring.profiles.active=it
or
-Dspring.profiles.active=production

FileInputStream FileNotFoundException but file definitely exists

I am encountering a weird FileNotFoundException with FileInputStream while working in Android Studio. Using this post, I ran some checks, but still cannot find the issue.
This is my code:
package com.mypackage;
import java.io.FileInputStream;
import java.sql.*;
import java.util.*;
import java.util.logging.Logger;
import java.io.File;
public class DatabaseDriver {
public DatabaseDriver(){
Properties properties = new Properties();
// get credentials from application.properties file
FileInputStream in = new FileInputStream("application.properties");
properties.load(in);
String url = properties.getProperty("url");
String user = properties.getProperty("user");
String password = properties.getProperty("password");
}
}
With some of the tips from the above post, I ran the following code in a debugging attempt:
public class DatabaseDriver {
public DatabaseDriver(){
File file = new File("application.properties");
System.out.println(new File(".").getAbsolutePath());
System.out.println(new File("application.properties").getAbsolutePath());
System.out.println(file.exists());
System.out.println(file.canRead());
System.out.println(file.isDirectory());
}
}
And the output when I create a DatabaseDriver instance in a main:
C:\Users\erin\AndroidStudioProjects\RecCenter\.
C:\Users\erin\AndroidStudioProjects\RecCenter\application.properties
true
true
false
That all seems fine, so I'm a little lost.

Default constructor cannot handle exception type FileNotFoundException thrown by implicit super constructor. Must define an explicit constructor

I tried FileNotFoundException and try, catch but did not help. I think problem is here
InputStream serviceAccount = new FileInputStream("/src/main/resources/static/FirebaseAdminSDKJava.json");
Full class source code:
package uz.xose.webapp;
import java.io.FileInputStream;
import java.io.InputStream;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.google.auth.oauth2.GoogleCredentials;
import com.google.cloud.firestore.Firestore;
import com.google.firebase.FirebaseApp;
import com.google.firebase.FirebaseOptions;
import com.google.firebase.cloud.FirestoreClient;
#RestController
public class HelloController {
InputStream serviceAccount = new FileInputStream("/src/main/resources/static/FirebaseAdminSDKJava.json");
GoogleCredentials credentials = GoogleCredentials.fromStream(serviceAccount);
FirebaseOptions options = new FirebaseOptions.Builder()
.setCredentials(credentials)
.build();
FirebaseApp.initializeApp(options);
Firestore db = FirestoreClient.getFirestore();
#RequestMapping("/")
public String index() {
return "This is the index!\n";
}
#RequestMapping("/hello")
public String index2() {
return "Hello, World!\n";
}
}
I am using Spring framework.
FirebaseAdminSDKJava.json located: src -> main -> resources -> static -> FirebaseAdminSDKJava.json
"/src/main/resources/static/FirebaseAdminSDKJava.json" is a relative file path. Depending on where your application is running, this file may or may not be in that position. Once built and deployed, the "src" dir won't be there, only in development.
Instead, load this file from the classpath. See this answer:
How to really read text file from classpath in Java
Classpath includes what you have inside you resources directory. please try this
1. InputStream in = this.getClass().getClassLoader()
.getResourceAsStream("FirebaseAdminSDKJava.json");
2 classpath:static/FirebaseAdminSDKJava.json
For debugging,
1. start eclipse in debugger mode or put your code in try block and instead of catching FileNotFoundException catch parent exception "Exception".
sample ex
try{
//your code
}catch(Exception ex){
ex.printStackTrace();
}
printStackTrace() will show us the actual root cause of the issue
hope it will work for you

Can a Jar File be updated programmatically without rewriting the whole file?

It is possible to update individual files in a JAR file using the jar command as follows:
jar uf TicTacToe.jar images/new.gif
Is there a way to do this programmatically?
I have to rewrite the entire jar file if I use JarOutputStream, so I was wondering if there was a similar "random access" way to do this. Given that it can be done using the jar tool, I had expected there to be a similar way to do it programmatically.
It is possible to update just parts of the JAR file using Zip File System Provider available in Java 7:
import java.net.URI;
import java.nio.file.FileSystem;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.HashMap;
import java.util.Map;
public class ZipFSPUser {
public static void main(String [] args) throws Throwable {
Map<String, String> env = new HashMap<>();
env.put("create", "true");
// locate file system by using the syntax
// defined in java.net.JarURLConnection
URI uri = URI.create("jar:file:/codeSamples/zipfs/zipfstest.zip");
try (FileSystem zipfs = FileSystems.newFileSystem(uri, env)) {
Path externalTxtFile = Paths.get("/codeSamples/zipfs/SomeTextFile.txt");
Path pathInZipfile = zipfs.getPath("/SomeTextFile.txt");
// copy a file into the zip file
Files.copy( externalTxtFile,pathInZipfile,
StandardCopyOption.REPLACE_EXISTING );
}
}
}
Yes, if you use this opensource library you can modify it in this way as well.
https://truevfs.java.net
public static void main(String args[]) throws IOException{
File entry = new TFile("c:/tru6413/server/lib/nxps.jar/dir/second.txt");
Writer writer = new TFileWriter(entry);
try {
writer.write(" this is writing into a file inside an archive");
} finally {
writer.close();
}
}

How to direct std input from file in Eclipse

How we can take input from the file in the Eclipse?
Just like we direct the I/O from the file from the command line.
java MyProgram < input.txt >output.txt
I am unable to direct the input.
but output directing is easy.
Just go->Run->Run->Configurations->Common
Why don't you use File instead of redirection?
Your program will have a fileName as input and then write the result in a file.
If you need necessarily use the default in you can do something like this:
System.setIn(new FileInputStream("testFile.txt"));
a sample of how it works follows:
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
public class TestSystemIn {
public static void main(final String[] args) throws IOException {
// prepare test
FileOutputStream fos = new FileOutputStream("testFile.txt");
fos.write("testToken".getBytes());
// configure env
System.setIn(new FileInputStream("testFile.txt"));
// perform read test
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("read: " + br.readLine());
}
}
The output could be done in the same way using:
System.setOut(new PrintStream("testFile.txt"));

Categories