Java .jar fails to start because of loading jcombobox data from file - java

I am beginner with Java and I have tried to make my app better.
So I have a method to fill the jcombobox with items from text file.
The method is
private void fillComboBox(JComboBox combobox, String filepath) throws FileNotFoundException, IOException {
BufferedReader input = new BufferedReader(new FileReader(filepath));
List<String> strings = new ArrayList<String>();
try {
String line = null;
while ((line = input.readLine()) != null) {
strings.add(line);
}
} catch (FileNotFoundException e) {
System.err.println("Error, file " + filepath + " didn't exist.");
} finally {
input.close();
}
String[] lineArray = strings.toArray(new String[]{});
for (int i = 0; i < lineArray.length - 1; i++) {
combobox.addItem(lineArray[i]);
}
}
And I am using it correctly
fillComboBox(jCombobox1, "items");
the text file with items is in my root directory of netbeans project.
It works perfectly when running the app from netbeans. But when I build the project and create .jar file. It does not run. I tried to run it from comand line.
This is what I got.
java.io.FileNotFoundException: items(System cannot find the file.)
How to deal with this? I didnt found anything. I dont know where is problem since it works nice in netbeans. Thank you very much for any help.

Is the .jar file in the same root directory?
Your exported .jar file might be working from a different directory, and not be able to find the text file.
Try placing the exported Jar in the same directory as the text file.
My example:
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JComboBox;
import javax.swing.JOptionPane;
public class test {
public static void main(String[] args) throws FileNotFoundException, IOException{
JComboBox box = new JComboBox();
fillComboBox(box, "C:\\path\\test.txt");
JOptionPane.showMessageDialog(null, box);
}
private static void fillComboBox(JComboBox combobox, String filepath) throws FileNotFoundException, IOException {
BufferedReader input = new BufferedReader(new FileReader(filepath));
List<String> strings = new ArrayList<String>();
try {
String line = null;
while ((line = input.readLine()) != null) {
strings.add(line);
}
} catch (FileNotFoundException e) {
System.err.println("Error, file " + filepath + " didn't exist.");
} finally {
input.close();
}
String[] lineArray = strings.toArray(new String[] {});
for (int i = 0; i < lineArray.length - 1; i++) {
combobox.addItem(lineArray[i]);
}
}
}

Related

JAVA - not able to update data in file that is "resources" folder

I am a little perplexed by the behavior I see in my proof-of-concept test program.
My Java application uses a file that is placed in "resource" folder in the Java project. The application will occasionally read numeric data from it, use it, increment the number and write it back to the same file for the next cycle.
The following test application mimics the above (wanted) behavior:
public class ReadWriteFile {
private static final String TEMP_EMAIL_ID_DATAFILE_PATH = "main/resources/TempEmailId.dat";
public static void main(String[] args) throws ParseException {
try {
int id = readTempId();
System.out.println("Current value = " + id);
writeTempId(id+5);
System.out.println("Updated value = " + readTempId());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static int readTempId() throws IOException {
InputStream is = ReadWriteFile.class.getClassLoader().getResourceAsStream(TEMP_EMAIL_ID_DATAFILE_PATH);
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String line = null;
int currentValue = 0;
while ((line = br.readLine()) != null) {
currentValue = Integer.parseInt(line);
}
br.close();
return currentValue;
}
public static void writeTempId(int currentId) throws IOException {
BufferedWriter bw = new BufferedWriter(new FileWriter("src" + File.separator + TEMP_EMAIL_ID_DATAFILE_PATH));
bw.write(Integer.toString(Math.abs(currentId)));
bw.flush();
bw.close();
return;
}
}
When I run the test, the following is seen:
Current value = 100000054
Updated value = 100000054
My gut feeling is that the use of
ReadWriteFile.class.getClassLoader().getResourceAsStream(TEMP_EMAIL_ID_DATAFILE_PATH);
is causing the issue. I am using this to access the file within the JAVA project.
Can it be true?
Also, note that for creating the BufferedWriter object, I have to pre-pend the Java constant with "src/" - else the file could not be found :(
Thanks.
Resources are intended to be read-only. The only way they could become writable is if they were extracted into the file system, but that's not how they are intended to be used and is not portable as resources are normally in a jar. Write to a file instead
This should work:
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.URISyntaxException;
import java.net.URL;
import java.text.ParseException;
public class ReadWriteFile {
private static final String TEMP_EMAIL_ID_DATAFILE_PATH = "TempEmailId.dat";
public static void main(String[] args) throws ParseException, URISyntaxException {
try {
int id = readTempId();
System.out.println("Current value = " + id);
writeTempId(id+5);
System.out.println("Updated value = " + readTempId());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static int readTempId() throws IOException {
InputStream is = ReadWriteFile.class.getClassLoader().getResourceAsStream(TEMP_EMAIL_ID_DATAFILE_PATH);
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String line = null;
int currentValue = 0;
while ((line = br.readLine()) != null) {
currentValue = Integer.parseInt(line);
}
br.close();
return currentValue;
}
public static void writeTempId(int currentId) throws IOException, URISyntaxException {
URL resource = ReadWriteFile.class.getClassLoader().getResource(TEMP_EMAIL_ID_DATAFILE_PATH);
File file = new File(resource.toURI());
BufferedWriter bw = new BufferedWriter(new FileWriter(file));
bw.write(Integer.toString(Math.abs(currentId)));
bw.flush();
bw.close();
return;
}
}
The 2 key lines for writing to file was doing it as such:
URL resource = ReadWriteFile.class.getClassLoader().getResource(TEMP_EMAIL_ID_DATAFILE_PATH);
File file = new File(resource.toURI());

Start and stop postgreSQL service through java code

I have one requirement where I need to start and stop postgreSQL service through java code. I have written below code but I am getting below error:
System error 5 has occurred.
Access is denied.
System error 5 has occurred.
Access is denied.
Below is my code:
package frontend.guifx.pginstallation;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import common.core.Logger;
import frontend.guifx.util.ConstPG;
public class StartAndStopPostgres {
public static String version = "9.5";
public static void main(String[] args){
try {
System.out.println("Execution starts");
copyPostgreSqlConfFileAndRestartPg();
System.out.println("Execution finished");
} catch (IOException | InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private static void copyPostgreSqlConfFileAndRestartPg() throws IOException, InterruptedException {
// TODO Auto-generated method stub
Path path = Paths.get("data/PGLogs");
//if directory exists?
if (!Files.exists(path)) {
try {
Files.createDirectories(path);
} catch (IOException e) {
//fail to create directory
e.printStackTrace();
}
}
Logger.print(StartAndStopPostgres.class, new String[] { "Copying postgresql.conf file ........" });
Path source = Paths.get("data/postgresql.windows.conf");
String copyConfFileTo = getInstallationPath(version);
copyConfFileTo = copyConfFileTo.substring(0, copyConfFileTo.lastIndexOf("\\"));
Path outputDirectoryPath = Paths.get(copyConfFileTo+File.separator+"data");
Files.copy(source, outputDirectoryPath.resolve(outputDirectoryPath.getFileSystem().getPath("postgresql.conf")), StandardCopyOption.REPLACE_EXISTING);
Logger.print(StartAndStopPostgres.class, new String[] { "Tunning datbase starts........" });
Runtime rt = Runtime.getRuntime();
final File file = new File(System.getProperty("java.io.tmpdir") + File.separator + ConstPG.CREATE_RESTART_PG_BAT_FILE);
PrintWriter writer = new PrintWriter(file, "UTF-8");
writer.println("net stop postgresql-x64-"+version);
writer.println("net start postgresql-x64-"+version);
writer.close();
String executeSqlCommand = file.getAbsolutePath();
Process process = rt.exec(executeSqlCommand);
/*final List<String> commands = new ArrayList<String>();
commands.add("cmd.exe");
commands.add("/C");
commands.add("net stop postgresql-x64-9.5");
commands.add("net start postgresql-x64-9.5");
ProcessBuilder b = new ProcessBuilder(commands);
Process process = b.start();*/
//public static final String PG_RESTART_PG_LOG_FILE = PG_LOGS+"/pgRestartProcess.log";
File createPgRestartProcessFile = new File(ConstPG.PG_RESTART_PG_LOG_FILE);
redirectProcessExecutionOutput(process, createPgRestartProcessFile);
int exitVal = process.waitFor();
Logger.print(StartAndStopPostgres.class, new String[] { "EXIT VALUE after tunning the PostgreSql database :::::::::::::::::::::" + exitVal + " Logs written to file at: " + createPgRestartProcessFile.getAbsolutePath() });
}
public static String getInstallationPath( String version) {
//public static final String PROGRAMME_FILES = "C:\\Program Files\\";
// public static final String PROGRAMME_FILES_X86 = "C:\\Program Files (x86)\\";
// public static final String POSTGRESQL = "PostgreSQL";
// public static final String PSQL_PATH = "\\bin\\psql.exe";
//Const values used below are as above
String psql = findFile(ConstPG.PROGRAMME_FILES, ConstPG.POSTGRESQL + "\\" + version + ConstPG.PSQL_PATH);
if (psql == null) {
psql = findFile(ConstPG.PROGRAMME_FILES_X86, ConstPG.POSTGRESQL + "\\" + version + ConstPG.PSQL_PATH);
}
if(psql != null){
psql = psql.substring(0, psql.lastIndexOf("\\"));
}
return psql;
}
public static String findFile(String directoryName, String fileName) {
File directory = new File(directoryName);
// get all the files from a directory
File[] fList = directory.listFiles();
String absolutePath;
if (fList != null) {
for (File file : fList) {
if (file.isFile()) {
absolutePath = file.getAbsolutePath();
if (absolutePath.contains(fileName))
return (absolutePath);
} else if (file.isDirectory()) {
absolutePath = findFile(file.getAbsolutePath(), fileName);
if (absolutePath != null)
return (absolutePath);
}
}
}
return (null);
}
private static void redirectProcessExecutionOutput(Process process, File processFile) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(process.getErrorStream()));
String line = null;
FileWriter fw = new FileWriter(processFile.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
while ((line = reader.readLine()) != null) {
Logger.print(StartAndStopPostgres.class, new String[] { line });
bw.write(line);
bw.newLine();
}
bw.close();
}
}
If I start my eclipse as an Administrator then this works fine. Also if I run start and stop commands on command prompt (which is opened as an Administrator i.e. right click on command prompt icon and click 'run as Administrator') then they execute successfully. But if I run the commands on normal command prompt (which is not opened as a administrator) then I get the same error there as well.
Please advise if there is any solution or any approach to solve this problem.
In java there is a option to run windows cmd as administrator
replace your code "commands.add("cmd.exe");" with below code and try
commands.add("runas /profile /user:ADMINUSERNAME \"cmd.exe");

how to read the data from the files of a directory

public class FIlesInAFolder {
private static BufferedReader br;
public static void main(String[] args) throws IOException {
File folder = new File("C:/filesexamplefolder");
FileReader fr = null;
if (folder.isDirectory()) {
for (File fileEntry : folder.listFiles()) {
if (fileEntry.isFile()) {
try {
fr = new FileReader(folder.getAbsolutePath() + "\\" + fileEntry.getName());
br = new BufferedReader(fr);
System.out.println(""+br.readLine());
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
finally {
br.close();
fr.close();
}
}
}
}
}
}
how to print the first word from first file of a directory and the second word from second file and third word from a third file of the same directory.
i am able to open directory and print the line from each file of the directory,
but tell me how to print the first word from first file and second word from second file and so on . .
Something like the below will read first word from first file, second word from second file, ... nth word from nth file. You'll likely want to do some additional work to improve the codes stability.
import java.io.File;
import java.io.IOException;
import java.io.FileReader;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
public class SOAnswer {
private static void printFirst(File file, int offset) throws FileNotFoundException, IOException {
FileReader fr = new FileReader(file);
BufferedReader br = new BufferedReader(fr);
String line = null;
while ( (line = br.readLine()) != null ) {
String[] split = line.split(" ");
if(split.length >= offset) {
String targetWord = split[offset];
}
// we do not care if files are read that do not match your requirements, or
// for reading complete files as you only care for the first word
break;
}
br.close();
fr.close();
}
public static void main(String[] args) throws Exception {
File folder = new File(args[0]);
if(folder.isDirectory()) {
int offset = 0;
for(File fileEntry : folder.listFiles()) {
if(fileEntry.isFile()) {
printFirst(fileEntry, offset++); // handle exceptions if you wish
}
}
}
}
}

Java I/O writing, mixingcase and getExtension problems

I am changing names of all files in directory and if it's text file I am changing the content but it doesn't seem to work the name of the file is changed right but content is blank/gone heres is my code:
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import org.apache.commons.io.FilenameUtils;
public class FileOps {
public static File folder = new File(
"C:\\Users\\N\\Desktop\\New folder\\RenamingFiles\\src\\renaming\\Files");
public static File[] listOfFiles = folder.listFiles();
public static void main(String[] argv) throws IOException {
toUpperCase();
}
public static void toUpperCase() throws FileNotFoundException {
for (int i = 0; i < listOfFiles.length; i++) {
if (listOfFiles[i].isFile()) {
String newname = mixCase(listOfFiles[i].getName());
if (listOfFiles[i].renameTo(new File(folder, newname))) {
String extension = FilenameUtils
.getExtension(listOfFiles[i].getName());
if (extension.equals("txt") || extension.equals("pdf")
|| extension.equals("docx")
|| extension.equals("log")) {
rewrite(listOfFiles[i]);
System.out.println("Done");
}
}
} else {
System.out.println("Nope");
}
}
}
public static String mixCase(String in) {
StringBuilder sb = new StringBuilder();
if (in != null) {
char[] arr = in.toCharArray();
if (arr.length > 0) {
char f = arr[0];
boolean first = Character.isUpperCase(f);
for (int i = 0; i < arr.length; i++) {
sb.append((first) ? Character.toLowerCase(arr[i])
: Character.toUpperCase(arr[i]));
first = !first;
}
}
}
return sb.toString();
}
public static void rewrite(File file) throws FileNotFoundException {
FileReader reader = new FileReader(file.getAbsolutePath());
BufferedReader inFile = new BufferedReader(reader);
try {
FileWriter fwriter = new FileWriter(file.getAbsolutePath());
BufferedWriter outw = new BufferedWriter(fwriter);
while (inFile.readLine() != null) {
String line = mixCase(inFile.readLine());
outw.write(line);
}
inFile.close();
outw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
There is several issue with your code:
Your rewrite function is perform on old name File. It should be done on the renamed File:
String newname = mixCase(listOfFiles[i].getName());
File renamedFile = new File(folder, newname);
if (listOfFiles[i].renameTo(renamedFile )) {
String extension = FilenameUtils
.getExtension(listOfFiles[i].getName());
if (extension.equals("txt") || extension.equals("pdf")
|| extension.equals("docx")
|| extension.equals("log")) {
rewrite(renamedFile);
System.out.println("Done");
}
}
you are trying to read docx and pdf file like regular text file. This cannot work. You will have to use external library like POI and pdf Box
Your rewrite function is not safe. You must unsure to close the ressources:
FileReader reader = null;
BufferedReader inFile = null;
try {
reader = new FileReader(file.getAbsolutePath());
inFile = new BufferedReader(reader);
FileWriter fwriter = new FileWriter(file.getAbsolutePath());
BufferedWriter outw = new BufferedWriter(fwriter);
while (inFile.readLine() != null) {
String line = mixCase(inFile.readLine());
outw.write(line);
}
} catch (IOException e) {
e.printStackTrace();
}finally
{
if(infile != null)
inFile.close();
if(reader != null)
reader .close();
}
You can't re-write a file on top of itself. you need to write the new content to a new file, then rename again.

Error: Could not find or load main class ReadFile recieved when attempting to run code [duplicate]

This question already has answers here:
Running a Java Program
(5 answers)
Closed 8 years ago.
When I run some code I have compiled (with no errors) I receive the following error:
Error: Could not find or load main class ReadFile
The code I am trying to run is the file ReadFile.java:
import java.io.IOException;
import java.io.FileReader;
import java.io.BufferedReader;
public class ReadFile {
public static void main(String[] args) throws IOException {
String file_name = "hello.txt";
try {
ReadFile file = new ReadFile(file_name);
String[] aryLines = file.OpenFile();
int i;
for (i=0; i<aryLines.length; i++) {
System.out.println(aryLines[i]);
}
}
catch (IOException e) {
System.out.println(e.getMessage() );
}
}
private String path;
public ReadFile(String file_path) {
path = file_path;
}
public String[] OpenFile() throws IOException {
FileReader fr = new FileReader(path);
BufferedReader textReader = new BufferedReader(fr);
int numberOfLines = readLines();
String[] textData = new String[numberOfLines];
int i;
for (i=0;i<numberOfLines;i++) {
textData[i] = textReader.readLine();
}
textReader.close();
return textData;
}
int readLines() throws IOException {
FileReader file_to_read = new FileReader(path);
BufferedReader bf = new BufferedReader(file_to_read);
String aLine;
int numberOfLines = 0;
while (( aLine = bf.readLine()) != null) {
numberOfLines++;
}
bf.close();
return numberOfLines;
}
}
and hello.txt is as follows:
Hello World
Hello Solar System
Hello Galaxy
I am a beginner and am not sure why I am returned with this error, can anyone help?
First of all, change directories to the location of your source file..
Use the Java Compiler to compile the source file to a .class file
javac ReadFile.java
Now use Java to run the resulting .class file...
java ReadFile
(Note, I didn't have a file to read, but that wasn't my goal)
**** WARNING ****
This will only work if the ReadFile.java file does not start with a package declaration. If it does, it will change the way that the class has to be run!!

Categories