From test.java, how can I access for reading the Contact.xml file located in the contacts.jar library ?
The bellow code returns null.
package views;
import fr.hznteam.contacts.Contact;
import fr.hznteam.errors.ResourceException;
import java.io.InputStream;
public class Test {
private static final String TAG = "Test ";
public static void main(String[] args) throws ResourceException {
InputStream is = Contact.class.getResourceAsStream("/fr/hznteam/contacts/sql/Contact.xml");
System.out.println(TAG + "resource from jar " + is);
}
The package structure :
this works (see above comment). Inside an object instance use
getClass().getResourceAsStream("/absolute/class_path/to/resource.file"))
Related
I work on my Spring Boot app which uses Spring API client as a maven depencency. When I use it in my code, it logs data. How can I turn it off? Where shall I place log4j.properties to actually work? I tried inside resources and also inside folder with my service which uses it.
package com.example.demo.service;
import com.wrapper.spotify.SpotifyApi;
import com.wrapper.spotify.SpotifyHttpManager;
import com.wrapper.spotify.exceptions.SpotifyWebApiException;
import com.wrapper.spotify.model_objects.credentials.AuthorizationCodeCredentials;
import com.wrapper.spotify.requests.authorization.authorization_code.AuthorizationCodeRequest;
import org.apache.hc.core5.http.ParseException;
import java.io.IOException;
import java.net.URI;
import java.util.concurrent.CancellationException;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionException;
public class AuthorizationCodeExample {
private static final String clientId = "";
private static final String clientSecret = "";
private static final URI redirectUri = SpotifyHttpManager.makeUri("");
private static final String code = "";
private static final SpotifyApi spotifyApi = new SpotifyApi.Builder()
.setClientId(clientId)
.setClientSecret(clientSecret)
.setRedirectUri(redirectUri)
.build();
private static final AuthorizationCodeRequest authorizationCodeRequest = spotifyApi.authorizationCode(code)
.build();
public static void authorizationCode_Sync() {
try {
final AuthorizationCodeCredentials authorizationCodeCredentials = authorizationCodeRequest.execute();
// Set access and refresh token for further "spotifyApi" object usage
spotifyApi.setAccessToken(authorizationCodeCredentials.getAccessToken());
spotifyApi.setRefreshToken(authorizationCodeCredentials.getRefreshToken());
System.out.println("Expires in: " + authorizationCodeCredentials.getExpiresIn());
} catch (IOException | SpotifyWebApiException | ParseException e) {
System.out.println("Error: " + e.getMessage());
}
}
public static void main(String[] args) {
authorizationCode_Sync();
}
}
This is my project tree:
https://imgur.com/mS676gw
logging.level.*=LEVEL
There are different levels available, the one you are looking for is OFF. So just add the following line into your application.properties file
logging.level.*=OFF
It should be resources folder. But did you made changes inside the file to turn off logs ?
log4j.rootLogger=OFF, Note that this has the highest priority and will turn off all logging.
I have a method as follows:
public(String input_filename, String output_filename)
{
//some content
}
how to create an input_filename at run time and read the input_filename .I have to pass input_filename as a parameter
Please be patient as I am new to Java
Here a complete sample:
Save it as Sample.java
compile it with: javac Sample.java
run it with: java Sample "in.txt" "out.txt"
or: java Sample
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
public class Sample {
public static void main(String[] args) throws IOException {
if(args.length == 2)
{
doFileStuff(args[0],args[1]);
}
else {
doFileStuff("in.txt","out.txt");
}
}
public static void doFileStuff(String input_filename, String output_filename) throws IOException {
if(!Files.exists(Paths.get(input_filename)))
{
System.err.println("file not exist: " + input_filename);
return;
}
if(!Files.exists(Paths.get(output_filename)))
{
System.err.println("file still exist, do not overwrite it: " + output_filename);
return;
}
String content = new String(Files.readAllBytes(Paths.get(input_filename)));
content += "\nHas added something";
Files.write(Paths.get(output_filename), content.getBytes(StandardCharsets.UTF_8));
}
}
I'm unsure what you want to do with this method, but I hope this can help you a bit.
If you want inputs during runtime, use the Scanner class. A guide on how to use it here
Also if you want an output in your class you should use "return", and not have it as a parameter.
Do note that you haven't named your class yet, or specified the output type.
How it could look:
public String className(String input){
return input;
}
i'm trying to copy all the files inside a directory to another(but i want it to not copy the folders). I'm trying to use Files.copy but i'm getting this error:
Exception in thread "main" java.nio.file.FileAlreadyExistsException:
Here's my actual code:
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
public class Exercici1 {
public static void copiarArchivos(String pathSource,String pathOutcome, String sufix) throws IOException {
File origen = new File(pathSource);
String[] contenidoOrigen = origen.list();
for(String string:contenidoOrigen){
File interno = new File(origen,string);
if (interno.isDirectory()){
copiarArchivos(interno.getPath(),pathOutcome,sufix);
} else {
Path targetOutcome = Paths.get(pathOutcome);
Path targetSource = Paths.get(interno.getPath());
Files.copy(targetSource,targetOutcome);
}
}
}
public static void main(String[] args) throws IOException {
copiarArchivos("Vampiro_Mascarada","pruebaPDF",".pdf");
}
}
My folder structure is like this:
/out
/pruebasPDF
/src
/Vampiro_Mascarada
/1.pdf
/2.pfdf
/Images
/1.png
/2.png
You need to use to Files.copy(source,dest,CopyOption) with the REPLACE_EXISTING option.
I`m trying to import jcurses library to IntelliJ but get an error.
File -> Project Structure -> Modules -> import jar file.
Then in code:
import jcurses.widgets.Window;
class main {
public static void main(String[] args){
Window win = new Window(800, 600, true, "test");
win.setVisible(true);
}
Exception in thread "main" java.lang.ExceptionInInitializerError
at jcurses.system.InputChar.<clinit>(InputChar.java:25)
at jcurses.widgets.Window.<clinit>(Window.java:209)
at main.main(main.java:7)
Caused by: java.lang.RuntimeException: couldn't find jcurses library
at jcurses.system.Toolkit.getLibraryPath(Toolkit.java:121)
at jcurses.system.Toolkit.<clinit>(Toolkit.java:37)
Could someone point out where is my mistake?
Thanks in advance!
The answer is that dll must be in the same directory as jar file. Thanks to everyone!
Libray download url
https://sourceforge.net/projects/javacurses/files/javacurses/0.9.5/
The path of the library is in the root directory of the project
dynamically add the library
import java.io.File;
import java.lang.reflect.Field;
import java.util.Arrays;
public class LoadLibrary {
public static void main(String cor[]) throws Exception {
// Cargando librerias necesarias
loadLibraryJCourses();
}
public static void loadLibraryJCourses() throws Exception{
loadDynamicLibrary(new File("lib/bin/jcourses/").getAbsolutePath(),"libjcurses64");
}
private static void addLibraryPath(String pathToAdd) throws Exception {
final Field usrPathsField = ClassLoader.class.getDeclaredField("usr_paths");
usrPathsField.setAccessible(true);
//get array of paths
final String[] paths = (String[]) usrPathsField.get(null);
//check if the path to add is already present
for (String path : paths) {
if (path.equals(pathToAdd)) {
return;
}
}
//add the new path
final String[] newPaths = Arrays.copyOf(paths, paths.length + 1);
newPaths[newPaths.length - 1] = pathToAdd;
usrPathsField.set(null, newPaths);
}
private static void loadDynamicLibrary(String pathLibraryDirectory, String libraryName) throws Exception{
File pathLibraryFile = new File(pathLibraryDirectory);
addLibraryPath(pathLibraryFile.getAbsolutePath());
System.loadLibrary(libraryName);
}
}
In my application we are uploading image/audio/video files. I have allowed some fixed set of allowed extensions of each types. If the extension does not match the list of provided extensions then it won't upload, but if the user renames the .exe, .pdf file to .jpg or .png the it would clear the UI validations and servlet will be called and upload will happen. But later that would cause a problem. Is there any way to check the same at backend and then throw an Exception accordingly.
I have tried using :
import java.net.*;
public class FileUtils{
public static String getMimeType(String fileUrl) throws java.io.IOException {
FileNameMap fileNameMap = URLConnection.getFileNameMap();
String type = fileNameMap.getContentTypeFor(fileUrl);
return type;
}
public static void main(String args[]) throws Exception {
System.out.println(FileUtils.getMimeType("file:/home/kavinder/file.pdf"));
// this is a .jpg file renamed to .pdf
}
}
This is returning according to extension only. And
import javax.activation.MimetypesFileTypeMap;
import java.io.File;
class GetMimeType {
public static void main(String args[]) {
File f = new File("/home/kavinder/file.jpg");
System.out.println("Mime Type of " + f.getName() + " is " + new MimetypesFileTypeMap().getContentType(f));
}
}
This is always returning the mime type as: application/octet-streamThank you in advance