How can i load a text file with a runnable .jar file, It works fine when it's not jarred but after i jar the application it can't locate the file. Here's what i'm using to load the text file.
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
public class PriceManager {
private static Map<Integer, Double> itemPrices = new HashMap<Integer, Double>();
public static void init() throws IOException {
final BufferedReader file = new BufferedReader(new FileReader("prices.txt"));
try {
while (true) {
final String line = file.readLine();
if (line == null) {
break;
}
if (line.startsWith("//")) {
continue;
}
final String[] valuesArray = line.split(" - ");
itemPrices.put(Integer.valueOf(valuesArray[0]), Double.valueOf(valuesArray[1]));
}
System.out.println("Successfully loaded "+itemPrices.size()+" item prices.");
} catch (final IOException e) {
e.printStackTrace();
} finally {
if (file != null) {
file.close();
}
}
}
public static double getPrice(final int itemId) {
try {
return itemPrices.get(itemId);
} catch (final Exception e) {
return 1;
}
}
}
Thanks for any and all help.
There are two reasons for this. Either the file is now embedded within the Jar or it's not...
Assuming that the file is not stored within the Jar, you can use something like...
try (BufferedReader br = new BufferedReader(new InputStreamReader(PriceManager.class.getResourceAsStream("/prices.txt")))) {...
If the prices.txt file is buried with the package structure, you will need to provide that path from the top/default package to where the file is stored.
If the file is external to the class/jar file, then you need to make sure it resides within the same directory that you are executing the jar from.
if this is your package structure:
Correct way of retrieving resources inside runnable or.jar file is by using getResourceAsStream.
InputStream resourceStream = TestResource.class.getResourceAsStream("/resources/PUT_Request_ER.xml");
If you do getResource("/resources/PUT_Request_ER.xml"), you get FileNotFoundException as this resource is inside compressed file and absolute file path doesn't help here.
Related
I have an absolute file path in my java program that contains some text. This is the code:
import java.io.*;
import java.util.*;
public class RoughCode {
public static void main(String[] args) {
try {
File rules=new File("C:\\Users\\Owner\\Documents\\ICS4U\\Assignment 1\\GameShowRules.txt");
Scanner scan=new Scanner(rules);// scans the file 'rules'
while (scan.hasNextLine()) {
System.out.println(scan.nextLine());// outputs 'rules' to console
}
}
catch(Exception e) {
System.out.println("File not found");
System.exit(0);
}
}
}
Here, the code works just fine. The output I get is whatever is stored in the file, which is:
The rules of the game are:
You must answer 15 multiple-choice questions correctly in a row to win the jackpot.
You may quit at any time and keep the earnings.
However, what I need is a relative file path so that it runs on any laptop.
In an attempt to do that, I did:
import java.io.*;
import java.net.URI;
import java.util.*;
public class RoughCode {
public static void main(String[] args) {
try {
// Two absolute paths
File absolutePath1 = new File("C:\\Users\\Owner\\Documents\\ICS4U\\Assignment 1\\GameShowRules.txt");
File absolutePath2 = new File("C:\\Users\\Owner\\Documents\\ICS4U\\Assignment 1");
// convert the absolute path to URI
URI path1 = absolutePath1.toURI();
URI path2 = absolutePath2.toURI();
// create a relative path from the two paths
URI relativePath = path2.relativize(path1);
// convert the URI to string
String path = relativePath.getPath();
Scanner scan=new Scanner(path);
while (scan.hasNextLine()) {
System.out.println(scan.nextLine());
}
}
catch(Exception e) {
System.out.println("File not found");
System.exit(0);
}
}
}
This does not display the text I need. it just displays "GameshowRules.txt".
How do I get it to output the text stored in the file?
Thanks
Try to use BufferedReader and FileReader. My "data.txt" file is in the same folder as the java program, and works just fine.
I guess you know where will be file of your own program, so you can paste relative path to it.
It looks like this
public class Project {
public static void main(String[] args) throws IOException {
BufferedReader reader = new BufferedReader(new FileReader("data.txt"));
String data;
while ((data = reader.readLine()) != null) {
System.out.println(data);
}
}
}
I am stuck in this issue very badly. I was trying to unzip the zip file using java. I need to upload a zip file using jsp. In controller it accepts Multipart file. Then I have to unzip this file to some location say a temp directory. I did mulipartFile.transferTo('temp zipfile location'), to place a zip file. Under this location zip file will always be replaced. This (zipcopy) would be the source of zip file to be unziped later.. below is code snippet..
String zipcopy = env.getProperty("zipFileCopier");
file.transferTo(new File(zipcopy));
file is of type Multipart.
This is running well on windows environment. No issues at all. I changed the path in application.properties for Linux environment. What I found is -- it is just NOT creating any unziped directories in temp directory. I call unzip code here :
unziputility.unzip(zipcopy, destTemp);
File extractedDir = new File(destTemp+File.separator+multipartFileName+File.separator+"local");
if(extractedDir!=null && extractedDir.exists() && extractedDir.isDirectory()) {
System.out.println("TEST");
//business logic
}
TEST is not getting printed in Linux env. Also note that above code is in try catch block with ex.printstackTrace method used. However no exception is seen caught. Here is my UnzipUtility class:
UnzipUtility
package abc.xyz.re.util;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import org.springframework.stereotype.Component;
#Component
public class UnzipUtility {
private static final int BUFFER_SIZE = 9096;
public void unzip(String zipFilePath, String destDirectory) throws IOException {
File destDir = new File(destDirectory);
if (!destDir.exists()) {
destDir.mkdir();
}
ZipInputStream zipIn = new ZipInputStream(new FileInputStream(zipFilePath));
ZipEntry entry = zipIn.getNextEntry();
while (entry != null) {
String entryName = entry.getName();
String filePath = destDirectory + File.separator + entryName;
if (!entry.isDirectory()) {
extractFile(zipIn, filePath);
} else {
File dir = new File(filePath);
dir.mkdirs();
}
zipIn.closeEntry();
entry = zipIn.getNextEntry();
}
zipIn.close();
}
private void extractFile(ZipInputStream zipIn, String filePath) throws IOException {
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(filePath));
byte[] bytesIn = new byte[BUFFER_SIZE];
int read = 0;
while ((read = zipIn.read(bytesIn)) != -1) {
bos.write(bytesIn, 0, read);
}
bos.close();
}
}
above UnzipUtility when replaced with lingala zip4j..same issue. https://github.com/srikanth-lingala/zip4j.
application.properties
uploadDestTemp = /opt/temp
destDirectory = /opt/apache-tomcat-7.0.39/webapps/ROOT/root_/contents/crbt_tones
zipFileCopier = /opt/zip_download/zipfile.zip
in above application.properties file, uploadDestTemp is already created. Also zipFileCopier directory with zipfile.zip file is created
I re-tested this case by making sample code only for unziping the zip file from one location to other. Again it ran perfect in Windows. But failed in Linux. code below:
package package123;
public class Test4 {
public static void main(String[] args) {
System.out.println("testing...");
try {
UnzipUtility unzipUtility = new UnzipUtility();
String unzipLocation = "/opt/temp";
String zipFilePath = "/opt/zip_download/zipfile.zip";
unzipUtility.unzip(zipFilePath, unzipLocation);
}catch(Exception ex) {
ex.printStackTrace();
}
}
}
someone please help me to resolve this issue. kindly tell me why I am not able to use this code on my production Linux environment.
Today I encountered problems to launch a jar-file for the first time. Now I know (after unzipping the jar) that the textfiles did not come along when I did the export and creation of a jar-package of my program in Eclipse.
Why does the textfiles not come along with the class files? Where should I put those in the project?
I put the textfiles in the root of the project folder
Greaful for help
EDIT: probably I can do it manually in the cmd but I dont know what I should add in the programcode where the textfiles are loaded. Should I for instance impelent a classloader?
I know how to do so when loading images such as jpg org gif. But what if it is a textfile?
Here is the method responsible for loading textfiles
private void read(String text_file, int len, int index) {
String[] stringBuffer = new String[len];
File file = new File(text_file);
FileReader fileReader;
BufferedReader bufferedReader ;
try {
fileReader = new FileReader(file);
bufferedReader = new BufferedReader(fileReader);
String line;
int i = 0;
while ( (line = bufferedReader.readLine()) != null) {
stringBuffer[i] = line;
i++;
}
bufferedReader.close();
} catch (FileNotFoundException fnde) {
fnde.printStackTrace();
JOptionPane.showMessageDialog(null, "files could not be found", "Help", 0);
} catch (Exception e) {
e.printStackTrace();
}
splitString(stringBuffer, index);
}
I made an example from your code. The file text.txt is in the source folder under META-INF.
package test;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.InputStreamReader;
import javax.swing.JOptionPane;
public class ReadFile {
public static void main(String[] args) {
ReadFile o = new ReadFile();
o.read("test.txt", 2, 0);
}
private void read(String text_file, int len, int index) {
BufferedReader bufferedReader ;
String[] stringBuffer = new String[len];
try {
bufferedReader = new BufferedReader(new InputStreamReader(getClass().getResourceAsStream("/META-INF/".concat(text_file))));
String line;
int i = 0;
while ( (line = bufferedReader.readLine()) != null) {
stringBuffer[i] = line;
i++;
}
bufferedReader.close();
} catch (FileNotFoundException fnde) {
fnde.printStackTrace();
JOptionPane.showMessageDialog(null, "files could not be found", "Help", 0);
} catch (Exception e) {
e.printStackTrace();
}
splitString(stringBuffer, index);
}
private void splitString(String[] stringBuffer, int index) {
for(String line: stringBuffer) {
System.out.println(line);
}
}
}
Hope this helps.
Only folders/jars listed under -> Properties -> Java Build Path -> Order and Export will be exported into the JAR. Place the files into a folder, which is on your build path by
adding any folder as source folder ( -> Properties -> Java Build Path -> Source)
or putting the file into a sub-folder of your standard src folder.
the base folder of your project is not and should/can not be part of the export.
import java.io.File;
import org.apache.commons.io.FilenameUtils;
public class Tester {
public static void main(String[] args) {
String rootPath = "F:\\Java\\Java_Project";
File fRoot = new File(rootPath);
File[] fsSub = fRoot.listFiles();
for (File file : fsSub) {
if(file.isDirectory()) continue;
String fileNewPath = FilenameUtils.removeExtension(file.getPath()) + "\\" + file.getName();
File fNew = new File(fileNewPath);
try {
file.renameTo(fNew);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
I am trying to move the file to another directory,for instance,if the File path is
"C:\out.txt"
than I want to move to
"C:\out\out.txt"
If i try to print the original File and the new original information, the work well,But they just can not move successful.
I suggest to try Java 7 NIO2
Files.move(Path source, Path target, CopyOption... options)
simple: how do i read the contents of a directory in Java, and save that data in an array or variable of some sort? secondly, how do i open an external file in Java?
You can use java IO API. Specifically java.io.File, java.io.BufferedReader, java.io.BufferedWriter etc.
Assuming by opening you mean opening file for reading. Also for good understanding of Java I/O functionalities check out this link: http://download.oracle.com/javase/tutorial/essential/io/
Check the below code.
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
public class FileIO
{
public static void main(String[] args)
{
File file = new File("c:/temp/");
// Reading directory contents
File[] files = file.listFiles();
for (int i = 0; i < files.length; i++) {
System.out.println(files[i]);
}
// Reading conetent
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader("c:/temp/test.txt"));
String line = null;
while(true)
{
line = reader.readLine();
if(line == null)
break;
System.out.println(line);
}
}catch(Exception e) {
e.printStackTrace();
}finally {
if(reader != null)
{
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
You can use a class java.io.File to do that. A File is an abstract representation of file and directory pathnames. You can retrieve the list of files/directories within it using the File.list() method.
There's also the Commons IO package which has a variety of methods for manipulating files and directories.
import java.io.File;
import java.io.IOException;
import java.util.Collection;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.filefilter.FileFilterUtils;
public class CommonsIO
{
public static void main( String[] args )
{
// Read the contents of a file into a String
try {
String contents = FileUtils.readFileToString( new File( "/etc/mtab" ) );
} catch (IOException e) {
e.printStackTrace();
}
// Get a Collection of files in a directory without looking in subdirectories
Collection<File> files = FileUtils.listFiles( new File( "/home/ross/tmp" ), FileFilterUtils.trueFileFilter(), null );
for ( File f : files ) {
System.out.println( f.getName() );
}
}
}
public class StackOverflow {
public static void main(String[] sr) throws IOException{
//Read a folder and files in it
File f = new File("D:/workspace");
if(!f.exists())
System.out.println("No File/Dir");
if(f.isDirectory()){// a directory!
for(File file :f.listFiles()){
System.out.println(file.getName());
}
}
//Read a file an save content to a StringBuiilder
File f1 = new File("D:/workspace/so.txt");
BufferedReader br = new BufferedReader(new FileReader(f1));
StringBuilder sb = new StringBuilder();
String line = "";
while((line=br.readLine())!=null)
sb.append(line+"\n");
System.out.println(sb);
}
}