I'm trying to set a font "bilboregular.ttf" found in the resources folder under the root of the jar file. If i run from netbeans the font is set successfully, however if from the jar file it isn't
CODE:
main method:{
String s = System.getProperty("user.dir") + "\\src\\resources\\" + "bilboregular.ttf";
File a = new File(s);
if (a.exists()) {
this.loadFont(s);
} else {
this.loadFont(this.getClass().getResource("/resources/" + "bilboregular.ttf").getFile());
}
}
public void loadFont(String s) {
try {
font = java.awt.Font.createFont(java.awt.Font.TRUETYPE_FONT, new File(s));
font = font.deriveFont(Font.PLAIN, 20);
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
ge.registerFont(font);
setFonts();
} catch (Exception ex) {
}
}
public boolean setFonts() {
jLabel3.setFont(font);
jLabel4.setFont(font);
return true;
}
Your main can't use getClass() because its static (assuming you mean public static void main(String args[]) with "main").
Try this code:
InputStream is = getClass().getResourceAsStream("/resources/bilboregular.ttf");
Font f = Font.createFont(Font.TRUETYPE_FONT, is);
if this doesn't work: please post the structure of your JAR and and the thrown exception (eg. use a Logger in your catch Block).
Btw. an empty exceptionblock is not a good idea here since IO operations can fail in many cases.
Related
I have made the code which renames all the jpg files in a directory from 1 to n (number of files)..
if there were let say 50 jpg files that after running the program all the files are renamed to 1.jpg ,2.jpg and so on till 50.jpg
But i am facing the problem if I manually rename the file let say 50.jpg to aaa.jpg then again running the program doesn't rename that file
I have wasted one day to resove that issue
Kindly help me
Code:
public class Renaming {
private static String path; // string for storing the path
public static void main(String[] args) {
FileReader fileReader = null; // filereader for opening the file
BufferedReader bufferedReader = null; // buffered reader for buffering the data of file
try{
fileReader = new FileReader("input.txt"); // making the filereader object and paasing the file name
bufferedReader = new BufferedReader(fileReader); //making the buffered Reader object
path=bufferedReader.readLine();
fileReader.close();
bufferedReader.close();
}
catch (FileNotFoundException e) { // Exception when file is not found
e.printStackTrace();
}
catch (IOException e) { // IOException
e.printStackTrace();
}
finally {
File directory=new File(path);
File[] files= directory.listFiles(); // Storing the all the files in Array
int file_counter=1;
for(int file_no=0;file_no<files.length;file_no++){
String Extension=getFileExtension(files[file_no]); //getting the filw extension
if (files[file_no].isFile() && (Extension .equals("jpg")|| Extension.equals("JPG"))){ // checking that if file is of jpg type then apply renaming // checking thaat if it is file
File new_file = new File(path+"\\"+files[file_no].getName()); //making the new file
new_file.renameTo(new File(path+"\\"+String.valueOf(file_no+1)+".jpg")); //Renaming the file
System.out.println(new_file.toString());
file_counter++; // incrementing the file counter
}
}
}
}
private static String getFileExtension(File file) { //utility function for getting the file extension
String name = file.getName();
try {
return name.substring(name.lastIndexOf(".") + 1); // gettingf the extension name after .
} catch (Exception e) {
return "";
}
}`
first of all, you should use the path separator / . It's work on Windows, Linux and Mac OS.
This is my version of your problem to rename all files into a folder provide. Hope this will help you. I use last JDK version to speed up and reduce the code.
public class App {
private String path = null;
public static int index = 1;
public App(String path){
if (Files.isDirectory(Paths.get( path ))) {
this.path = path;
}
}
public void rename() throws IOException{
if ( this.path != null){
Files.list(Paths.get( this.path ))
.forEach( f ->
{
String fileName = f.getFileName().toString();
String extension = fileName.replaceAll("^.*\\.([^.]+)$", "$1");
try {
Files.move( f ,Paths.get( this.path + "/" + App.index + "." + extension));
App.index++;
} catch (IOException e) {
e.printStackTrace();
}
}
);
}
}
public static void main(String[] args) throws IOException {
App app = new App("c:/Temp/");
app.rename();
}
}
I have imported pdfbox-2.0.4.jar, fontbox-2.0.4.jar and commons-logging-1.1.1.jar into eclipse kepler. The programm runs on win10.
The console prints lots of such warnings
org.apache.pdfbox.pdmodel.font.PDCIDFontType2 <init>
WARNING: Using fallback font ArialUnicodeMS for CID-keyed TrueType font KaiTi_GB2312.
And I cannot access the image file with whole content. How can I fix it?
My code is like this:
public class PdfboxTest {
private static final String filePath = "xxx";
private static final String outputFilePath = "xxx";
public static void change(File inputFile, File outputFolder) throws IOException {
String totalFileName = inputFile.getName();
String fileName = totalFileName.substring(0,totalFileName.lastIndexOf("."));
PDDocument doc = null;
try {
doc = PDDocument.load(inputFile);
PDFRenderer pdfRenderer = new PDFRenderer(doc);
int pageCounter = 0;
for(PDPage page : doc.getPages())
{
BufferedImage bim = pdfRenderer.renderImageWithDPI(pageCounter, 300, ImageType.RGB);
ImageIOUtil.writeImage(bim, outputFilePath + "\\" + fileName + (pageCounter++) +".png", 300);
}
doc.close();
} finally {
if (doc != null) {
doc.close();
}
}
}
public static void main(String[] args) {
File inputFile = new File(filePath);
File outputFolder = new File(outputFilePath);
if(!outputFolder.exists()){
outputFolder.mkdirs();
}
try {
change(inputFile, outputFolder);
} catch (IOException e) {
e.printStackTrace();
}
}
}
As seen in the comments - the best solution is to install the missing font KaiTi_GB2312. The message Using fallback font means that the PDF references the mentioned font and didn't embed it, but can't find it on your computer, so PDFBox tried a fallback solution, in this case the ArialUnicodeMS font. Sadly such fallback solutions are not always perfect, which is why some glyphs were missing in the rendered image.
My programm shall communicate via RS232, therefore i use a .jar and two .dll's from RXTX. At the end I want to run it from a single .jar file.
To solve this problem i used this tutorial. But if I run the program from Eclipse (or after exporting from console) I get this exception:
java.lang.UnsatisfiedLinkError: no rxtxSerial in java.library.path thrown while loading gnu.io.RXTXCommDriver
Exception in thread "main" java.lang.UnsatisfiedLinkError: no rxtxSerial in java.library.path
Here is an minimal example of my code
private static final String LIB = "lib/";
private final static String RXTXPARALLEL = "rxtxParallel";
private final static String RXTXSERIAL = "rxtxSerial";
static {
try {
System.loadLibrary(RXTXSERIAL);
System.loadLibrary(RXTXPARALLEL);
} catch (UnsatisfiedLinkError e) {
loadFromJar();
}
}
public static void main(String[] args) {
//RS232 is this class
RS232 main = new RS232();
main.connect("COM15");
}
private static void loadFromJar() {
String path = "AC_" + new Date().getTime();
loadLib(path, RXTXPARALLEL);
loadLib(path, RXTXSERIAL);
}
private static void loadLib(String path, String name) {
name = name + ".dll";
try {
InputStream in = ResourceLoader.load(LIB + name);
File fileOut = new File(System.getProperty("java.io.tmpdir") + "/"
+ path + LIB + name);
OutputStream out = FileUtils.openOutputStream(fileOut);
IOUtils.copy(in, out);
in.close();
out.close();
System.load(fileOut.getAbsolutePath());
} catch (Exception e) {
e.printStackTrace();
}
}
private void connect(String portName) {
CommPortIdentifier portIdentifier;
try {
//Here the exception is thrown
portIdentifier = CommPortIdentifier.getPortIdentifier(portName);
} catch (NoSuchPortException exc) {
exc.printStackTrace();
return;
}
//... some other code
}
Is there a way to get an executable .jar file?
You have a few options. Try to copy the .dll files in the runtime folder and override the files at each start of your program. A second option is to copy the files in a fix folder and add the path of the folder to the environment variables in MS Windows. You can also override the files at each start.
Another possibility is to add the temporary folder to the MS Windows environment variables at runntime. But be careful with this solution, for more information read this post.
static {
try {
System.loadLibrary(RXTXSERIAL);
System.loadLibrary(RXTXPARALLEL);
} catch (UnsatisfiedLinkError exc) {
initLibStructure();
}
}
private static void initLibStructure() {
try {
//runntime Path
String runPath = new File(".").getCanonicalPath();
//create folder
File dir = new File(runPath + "/" + LIB);
dir.mkdir();
//get environment variables and add the path of the 'lib' folder
String currentLibPath = System.getProperty("java.library.path");
System.setProperty("java.library.path",
currentLibPath + ";" + dir.getAbsolutePath());
Field fieldSysPath = ClassLoader.class
.getDeclaredField("sys_paths");
fieldSysPath.setAccessible(true);
fieldSysPath.set(null, null);
loadLib(runPath, RXTXPARALLEL);
loadLib(runPath, RXTXSERIAL);
} catch (Exception e) {
e.printStackTrace();
}
}
private static void loadLib(String path, String name) {
name = name + ".dll";
try {
InputStream in = ResourceLoader.load(LIB + name);
File fileOut = new File(path + "/" + LIB + name);
OutputStream out = FileUtils.openOutputStream(fileOut);
IOUtils.copy(in, out);
in.close();
out.close();
System.load(fileOut.getAbsolutePath());
} catch (Exception e) {
e.printStackTrace();
}
}
I was wondering whether there is a way to take a given .jar file, selected with a JFileChooser, extract it and put it into a new directory. Then, take all the files from another directory, add it to the directory with the extracted .jar file, and then take all that and package it back up again.
I'm doing this because I want a really easy way to install mods for that game, minecraft, where you can just select your minecraft.jar, and make sure the files for the mod are in a folder, and wait a bit, as indicated by a JProgressBar.
This is all I have so far
import java.io.*;
import java.util.jar.*;
import javax.swing.*;
public class Main extends JFrame {
public Main() {
super("Auto-mod installer");
setSize(300, 60);
setLocationRelativeTo(null);
setResizable(false);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JProgressBar bar = new JProgressBar(0, 100);
add(bar);
setVisible(true);
}
public static void main(String[] args) {
Main m = new Main();
}
private void extract(File f) {
//Hrm...
}
private void addModFiles() {
//Uh...
}
private void repackage(File f) {
//What?
}
}
As you can see, I have no idea what I'm doing. I do know what the imports needed are, but that's about it. Help would be appreciated, ranting about anything I did wrong would get me mad. Thanks!
EDIT: If you know a way to get the same results, and it's not the way that I was looking for, please let me know how to do so. As long as I get the results I was looking for, it would be great. Thanks again!
The idea is relatively simple. You have a few gotchas (like what to do if files already exist and that kind of thing), but otherwise...
I'd start by having a look at JarFile
(I'm in the middle of another example, but when I get time, I'll post some stuff)
UPDATE with Example
public class JarTest {
protected static final String OUTPUT_PATH = "..."; // The place you want to extact the jar to
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
new JarTest();
}
public JarTest() {
try {
unjar();
// Copy new contents in...
jar();
} catch (IOException exp) {
exp.printStackTrace();
}
}
// This just recursivly lists through all the files to be included in the new jar
// We don't care about the directories, as we will create them from the file
// references in the Jar ourselves
protected List<File> getFiles(File path) {
List<File> lstFiles = new ArrayList<File>(25);
// If you want the directories, add the "path" to the list now...
File[] files = path.listFiles();
if (files != null && files.length > 0) {
for (File file : files) {
if (file.isDirectory()) {
lstFiles.addAll(getFiles(file));
} else {
lstFiles.add(file);
}
}
}
return lstFiles;
}
// Re-Jar the contents
// You should always attempt to jar back to a new file, as you may not want to effect the original ;)
public void jar() throws IOException {
JarOutputStream jos = null;
try {
String outputPath = OUTPUT_PATH;
// Create a new JarOutputStream to the file you want to create
jos = new JarOutputStream(new FileOutputStream("...")); // Add your file reference
List<File> fileList = getFiles(new File(OUTPUT_PATH));
System.out.println("Jaring " + fileList.size() + " files");
// Okay, I cheat. I make a list of all the paths already added to the Jar only create
// them when I need to. You could use "file.isDirectory", but that would mean you would need
// to ensure that the files were sorted to allow all the directories to be first
// or make sure that the directory reference is added to the start of each recursion list
List<String> lstPaths = new ArrayList<String>(25);
for (File file : fileList) {
// Replace the Windows file seperator
// We only want the path to this element
String path = file.getParent().replace("\\", "/");
// Get the name of the file
String name = file.getName();
// Remove the output path from the start of the path
path = path.substring(outputPath.length());
// Remove the leading slash if it exists
if (path.startsWith("/")) {
path = path.substring(1);
}
// Add the path path reference to the Jar
// A JarEntry is considered to be a directory if it ends with "/"
if (path.length() > 0) {
// At the trailing path seperator
path += "/";
// Check to see if we've already added it out not
if (!lstPaths.contains(path)) {
// At the path entry...we need need this to make it easier to
// extract the files at a later state. There is a way to cheat,
// but I'll let you figure it out
JarEntry entry = new JarEntry(path);
jos.putNextEntry(entry);
jos.closeEntry();
// Make sure we don't try to add the same path entry again
lstPaths.add(path);
}
}
System.out.println("Adding " + path + name);
// Create the actual entry for this file
JarEntry entry = new JarEntry(path + name);
jos.putNextEntry(entry);
// Write the entry to the file
FileInputStream fis = null;
try {
fis = new FileInputStream(file);
byte[] byteBuffer = new byte[1024];
int bytesRead = -1;
while ((bytesRead = fis.read(byteBuffer)) != -1) {
jos.write(byteBuffer, 0, bytesRead);
}
jos.flush();
} finally {
try {
fis.close();
} catch (Exception e) {
}
}
jos.closeEntry();
}
jos.flush();
} finally {
try {
jos.close();
} catch (Exception e) {
}
}
}
public void unjar() throws IOException {
JarFile jarFile = null;
try {
String outputPath = OUTPUT_PATH;
File outputPathFile = new File(outputPath);
// Make the output directories.
// I'll leave it up to you to decide how best to deal with existing content ;)
outputPathFile.mkdirs();
// Create a new JarFile reference
jarFile = new JarFile(new File("C:/hold/Java_Harmony.jar"));
// Get a list of all the entries
Enumeration<JarEntry> entries = jarFile.entries();
while (entries.hasMoreElements()) {
// Get the next entry
JarEntry entry = entries.nextElement();
// Make a file reference
File path = new File(outputPath + File.separator + entry.getName());
if (entry.isDirectory()) {
// Make the directory structure if we can
if (!path.exists() && !path.mkdirs()) {
throw new IOException("Failed to create output path " + path);
}
} else {
System.out.println("Extracting " + path);
// Extract the file from the Jar and write it to disk
InputStream is = null;
OutputStream os = null;
try {
is = jarFile.getInputStream(entry);
os = new FileOutputStream(path);
byte[] byteBuffer = new byte[1024];
int bytesRead = -1;
while ((bytesRead = is.read(byteBuffer)) != -1) {
os.write(byteBuffer, 0, bytesRead);
}
os.flush();
} finally {
try {
os.close();
} catch (Exception e) {
}
try {
is.close();
} catch (Exception e) {
}
}
}
}
} finally {
try {
jarFile.close();
} catch (Exception e) {
}
}
}
}
You can use this very simple library to pack/unpack jar file
JarManager
Very simple
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import fr.stevecohen.jarmanager.JarPacker;
import fr.stevecohen.jarmanager.JarUnpacker;
public class MyClass {
public void addFileToJar(String jarPath, String otherFilePath) {
try {
JarUnpacker jarUnpacker = new JarUnpacker();
File myJar = new File("./myfile.jar");
File otherFile = new File(otherFilePath);
Path unpackDir = Files.createTempDirectory(myJar.getName()); //create a temp directory to extract your jar
System.out.println("Unpacking in " + unpackDir.toString());
jarUnpacker.unpack(jarPath, unpackDir.toString()); //extraxt all files contained in the jar in temp directory
Files.copy(otherFile.toPath(), new File(unpackDir.toFile(), otherFile.getName()).toPath()); //copy your file
JarPacker jarRepacker = new JarPacker();
File newJar = new File("./maNewFile.jar");
System.out.println("Packing jar in " + newJar.getAbsolutePath());
jarRepacker.pack(unpackDir.toString(), newJar.getAbsolutePath()); //repack the jar with the new files inside
} catch (IOException e) {
e.printStackTrace();
}
}
}
You can also use maven dependency
<dependency>
<groupId>fr.stevecohen.jarmanager</groupId>
<artifactId>JarManager</artifactId>
<version>0.5.0</version>
</dependency>
You also need my repository
<repository>
<id>repo-reapersoon</id>
<name>ReaperSoon's repo</name>
<url>http://repo-maven.stevecohen.fr</url>
</repository>
Check the last version with the link bellow to use the last dependency
Please use my public issue tracker if you find some bugs
the code is below:
Font getFont(String fontPath) throws IOException, FontFormatException {
fis = new FileInputStream(fontPath);
bis = new java.io.BufferedInputStream(fis);
Font tmp = null;
try {
tmp = Font.createFont(Font.TRUETYPE_FONT, bis);
} catch (FontFormatException e) {
e.printStackTrace();
bis.close();
fis = new FileInputStream(fontPath);
bis = new java.io.BufferedInputStream(fis);
tmp = Font.createFont(Font.TYPE1_FONT, bis);
}
return tmp.deriveFont(96.0f);
}
this code is not always work!!!.
it will throw java.awt.FontFormatException for some font file, however, that font file can be open correctly in windows...why
it will first throw:
java.awt.FontFormatException: Font name not found
and then throw:
java.awt.FontFormatException: bad pfa font
Try running this on your computer. Replace rootPath with the path to your fonts.
public class FontLoader {
public static void main(String[] args) {
String rootPath = "/Library/Fonts";
File root = new File(rootPath);
if (root.canRead()) {
String[] fontFiles = root.list();
Font font = null;
for (String fontFile : fontFiles) {
try {
System.out.println(fontFile);
font = Font.createFont(Font.TRUETYPE_FONT, new File(root
+ "/" + fontFile));
System.out.println(font);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
}
You should be able to run indefinite number of times without fail, and if so then you might want to restructure your code somewhat - the stacking of close/open on your input streams looks somewhat suspicious. I say this without seeing where you are declaring those instance variables and what other code might be manipulating them.