How can I fix the following problem regarding the variable? - java

I have a class and inside it there is a baseDir variable which has been defined as follows:
public class experiment {
for (int exp = 0; exp < experimentCnt; exp++) {
String dirString = config.getClass().getSimpleName() + "_" + df.format(new Date());
String baseDir = new File(homeDir + "/" + dirString).getAbsolutePath();
System.out.println("Running simulation: " + dirString);
setCurrentDirectory(baseDir);
PrintWriter paramsLog = null;
try {
paramsLog = new PrintWriter(
new File("experimentParams.log").getAbsoluteFile(), "UTF-8");
paramsLog.println(params);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
Now, I want to use that baseDir variable in another class. How can I make it accessible?

Instead of making a new variable inside your function, you should just make a public variable outside of your function.
public class experiment {
public String baseDir;
for (int exp = 0; exp < experimentCnt; exp++) {
String dirString = config.getClass().getSimpleName() + "_" + df.format(new Date());
baseDir = new File(homeDir + "/" + dirString).getAbsolutePath();
System.out.println("Running simulation: " + dirString);
setCurrentDirectory(baseDir);
PrintWriter paramsLog = null;
try {
paramsLog = new PrintWriter(
new File("experimentParams.log").getAbsoluteFile(), "UTF-8");
paramsLog.println(params);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}

Related

How to execute java class in controller

Here I want to export to csv, I have ExportCsv.java, how do I run ExportCsv.java through the controller.
So what I want, when I click "Generate Report" in html it will run ExportCsv.java whose code is as below,
If there is someone who can help me in solving this problem
This is my ExportCsv.java
public class ExportCsv {
public static void exportCsv(String system_matter_id) {
try {
Date currentDate = new Date();
SimpleDateFormat dtFormat = new SimpleDateFormat("dd-MM-yyyy");
String date = dtFormat.format(currentDate);
// date = "26-05-2021";
String csv_file_path = "Maintenance Export " + "(" + date + ")" + ".csv";
OutputStream outputStream = new FileOutputStream(csv_file_path);
outputStream.write(239);
outputStream.write(187);
outputStream.write(191);
try (PrintWriter writer = new PrintWriter(new OutputStreamWriter(outputStream, "UTF-8"))) {
MaintenanceService maintenanceService = new MaintenanceService();
MaintenanceModel maintenanceModel = maintenanceService.getmaintenanceModel(system_matter_id);
String data_a = maintenanceModel.getData_A();
String data_b = maintenanceModel.getData_B();
StringBuilder sb = new StringBuilder();
// Header
sb.append("Data A");
sb.append(';');
sb.append("Data B");
sb.append('\n');
// Data
sb.append(data_a);
sb.append(';');
sb.append("data_b");
sb.append('\n');
writer.write(sb.toString());
writer.flush();
writer.close();
} catch (Exception e) {
}
} catch (Exception e) {
}
}
private static void moveFile(String src, String dest) {
Path result = null;
try {
result = Files.move(Paths.get(src), Paths.get(dest));
} catch (IOException e) {
System.out.println("Exception while moving file: " + e.getMessage());
}
if (result != null) {
System.out.println("File moved succesfully.");
} else {
System.out.println("File movement failed.");
}
}
}
This is my Controller
#RequestMapping(value = "export")
public void exportcsv(HttpServletResponse response) throws IOException {
response.setContentType("text/plain; charset=utf-8");
response.getClass();
}
This is my HTML
<a id="reportDownload" target="_blank" href="maintenance/export">Generate Report</a>
please help me in solving this case

Flatbuffer writing in binary file in android give only single response

I am new at flatbuffer. I had created a schema file from outside the project and adding the user(Monster as in Flatbuffer document) inside the binary via java code in android. everything works fine. but the time of reading binary file data it only gives me the user length 1. I had added 3 people but it's give me the length of monsters is 1 at the time of reading. can anyone help to figure this out. Here is the code->
this is the full code ->
enter code here
builder = new FlatBufferBuilder(1024);
public void addNewData(String emailOffset, String nameOffset,String
contactNoOffset, String DOJOffset, String departmentOffset,
String empIdOffset, float[] embeddingOffset)
{
int storeembedd = SingleJson.createEmbeddingVector(builder,
embeddingOffset);
int hereEmailOffset = builder.createString(emailOffset);
int hereNameOffset = builder.createString(nameOffset);
int hereContactOffset = builder.createString(contactNoOffset);
int hereDOJOffset = builder.createString(DOJOffset);
int hereDepartmentOffset=builder.createString(departmentOffset);
int hereImpIdOffset = builder.createString(empIdOffset);
int test = SingleJson.createSingleJson(builder, hereEmailOffset,
hereNameOffset, hereContactOffset
, hereDOJOffset, hereDepartmentOffset, hereImpIdOffset,
storeembedd);
int [] offsetOfMonster = new int[1];
offsetOfMonster[0] = test;
int temp = Monsters.createMonstersVector(builder,
offsetOfMonster);
Monsters.startMonsters(builder);
Monsters.addMonsters(builder, temp);
int orc = Monsters.endMonsters(builder);
builder.finish(orc);
byte[] buf1 = builder.sizedByteArray();
openAndAppenedInBinary(buf1);
}
private void openAndAppenedInBinary(byte[] buf1) {
FileOutputStream output = null;
try {
InputStream inputStream = new FileInputStream(newFile());
byte[] buffer = new byte[inputStream.available()];
if (inputStream.available() == 0) {
output = new FileOutputStream(newFile(), true);
output.write(buf1);
} else {
while (inputStream.read(buffer) != -1) {
output = new FileOutputStream(newFile(), true);
output.write(buffer);
output.write(buf1);
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
output.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
private String newFile() {
File file = new File(Environment.getExternalStorageDirectory()
+ "/Android/data/"
+ context.getPackageName()
+ "/binFile");
if (!file.exists()) {
if (!file.mkdir()) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
try {
Path dir = Paths.get(file.getAbsolutePath());
Files.createDirectory(dir);
} catch (IOException e) {
Path parentDir = Paths.get(file.getParent());
if (!Files.exists(parentDir)) {
try {
Files.createDirectories(parentDir);
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
}
}
}
File binFile = new File(file, "renamed.bin");
try {
FileWriter writer = new FileWriter(binFile);
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
return binFile.getAbsolutePath();
}
here is my reading code of flatbiffer->
new FlatParsingForPerticularId().execute(readRawResource(R.raw.renamed));//renamed is my bin file
private class FlatParsingForPerticularId extends AsyncTask {
#Override
protected String doInBackground(Object... params) {
byte[] buffer = (byte[]) params[0];
long startTime = System.currentTimeMillis();
ByteBuffer bb = ByteBuffer.wrap(buffer);
Monsters monsterList = Monsters.getRootAsMonsters(bb);
int length = monsterList.monstersLength();
SingleJson monster = null;
for (int i = 0; i < length; i++) {//here I m getting length 1 intead of 3
monster = monsterList.monsters(i);
if (i == outputval[0]) {
outputval[0] = (int) monster.EmpNo();
break;
}
}
long endTime = System.currentTimeMillis() - startTime;
String textToShow = "Elements: " + monsterList.monstersLength() + ": load time: " + endTime + "ms";
String[] monsterArr = monster.Name().split(" ");
return monsterArr[0];
}

JAVA Replacing line or strings in textfile not working

So i have made two methods that creates the file (createFile(); and one to fill the textfile with empty highscores if none are set.
public class HighscoreList {
static String highscore = null;
static PuzzleModel theModel;
static File file = null;
public static int nom;
public static int tu;
public static int nor;
public static String search = " ";
static String replace = "2";
static String numberOfRows = null;
static String timeUsed = " ";
static String numberOfMoves = " ";
public static void main(String[] args) {
createFile();
isEmptySetEmptyHighscore();
// checkScore(0);
getHighscore(0);
}
public static void createFile() {
file = new File("C:\\Users\\Thomas\\Eclipse Workspace\\15Puzzle\\15Puzzle\\src\\FifteenPuzzle\\ScoreBoard.txt");
System.out.println("Created file " + file.getName());
if (!file.exists()) {
System.out.println("File didn't exist creating new file");
try {
file.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public static void isEmptySetEmptyHighscore() {
try {
BufferedReader br = new BufferedReader(new FileReader(
"C:\\Users\\Thomas\\Eclipse Workspace\\15Puzzle\\15Puzzle\\src\\FifteenPuzzle\\ScoreBoard.txt"));
if (br.readLine() == null) {
setEmptyHighscoreFile();
}
} catch (IOException e) {
e.printStackTrace();
}
}
public static void setEmptyHighscoreFile() {
try {
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
System.out.println("File is empty, fills with empty fields");
for (int i = 3; i < 101; i++) {
bw.write(i + ":" + numberOfMoves + ":" + timeUsed+"\n");
}
bw.close();
System.out.println("Done");
} catch (IOException e) {
e.printStackTrace();
}
}
I have a getHighscore() that reads the two empty " " fields with moves and timeUsed. It is currently able to read this, but i cant write to those empty spaces in the textfile and replace them with actual numbers that i want.
EDIT: With the replace command it just adds it to the bottom of the file.
Is there something wrong with my code that re erases the text that i try to replace or how do i do it?
I tried something like this:
public static void writeToFile(int rows) {
try {
FileWriter fw = new FileWriter(file.getAbsoluteFile(),true);
BufferedWriter bw = new BufferedWriter(fw);
BufferedReader br = new BufferedReader(new FileReader(
"C:\\Users\\Thomas\\Eclipse Workspace\\15Puzzle\\15Puzzle\\src\\FifteenPuzzle\\ScoreBoard.txt"));
if(br.readLine().split(":")[0].equals(Integer.toString(rows+1))){
bw.write(br.readLine().replaceFirst(rows+2+": : ", "yes"));
System.out.println(" lel");
}
bw.close();
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
have you try this ?
String line = br.readLine();
if(line.split(":")[0].equals(Integer.toString(rows+1))){
bw.write(line.replaceFirst(rows+2+": : ", "yes"));
System.out.println(" lel");
}

>>> URI is not hierarchical

Sorry I'm new here but I have and issue I'm hoping someone can help me solve.
This code runs perfect while in eclipse, but after compiled it say's:
java.lang.IllegalArgumentException: URI is not hierarchical
Any help would be appropriated, thanks!
public void loadMods(String pkg) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException, InstantiationException {
List<Class<?>> classes = getClasses(pkg);
for(Class<?> c : classes) {
for (Method m : c.getMethods()) {
Object o = null;
o = c.newInstance();
if (m.getName().contains("load")) {
m.setAccessible(true);
m.invoke(o);
}
}
}
}
public static List<Class<?>> getClasses(String pkg) {
String pkgname = pkg;
List<Class<?>> classes = new ArrayList<Class<?>>();
File directory = null;
String fullPath;
String relPath = pkgname.replace('.', '/');
URL resource = ClassLoader.getSystemClassLoader().getResource(relPath);
if (resource == null) {
throw new RuntimeException("No resource for " + relPath);
}
fullPath = resource.getFile();
try {
directory = new File(resource.toURI());
} catch (URISyntaxException e) {
throw new RuntimeException(pkgname + " (" + resource + ") invalid URL / URI.", e);
} catch (IllegalArgumentException e) {
directory = null;
}
if (directory != null && directory.exists()) {
String[] files = directory.list();
for (int i = 0; i < files.length; i++) {
if (files[i].endsWith(".class")) {
String className = pkgname + '.' + files[i].substring(0, files[i].length() - 6);
try {
classes.add(Class.forName(className));
} catch (ClassNotFoundException e) {
throw new RuntimeException("ClassNotFoundException loading " + className);
}
} else {
String pkgnamex = pkgname + '.' + files[i];
List<Class<?>> classesx = new ArrayList<Class<?>>();
File directoryx = null;
String fullPathx;
String relPathx = pkgnamex.replace('.', '/');
URL resourcex = ClassLoader.getSystemClassLoader().getResource(relPathx);
if (resourcex == null) {
throw new RuntimeException("No resource for " + relPathx);
}
fullPathx = resourcex.getFile();
try {
directoryx = new File(resourcex.toURI());
} catch (URISyntaxException e) {
throw new RuntimeException(pkgnamex + " (" + resourcex + ") invalid URL / URI.", e);
} catch (IllegalArgumentException e) {
directoryx = null;
}
if (directoryx != null && directoryx.exists()) {
String[] filesx = directoryx.list();
for (int ix = 0; ix < filesx.length; ix++) {
if (filesx[ix].endsWith(".class")) {
String classNamex = pkgnamex + '.' + filesx[ix].substring(0, filesx[ix].length() - 6);
try {
classes.add(Class.forName(classNamex));
} catch (ClassNotFoundException e) {
throw new RuntimeException("ClassNotFoundException loading " + classNamex);
}
}
}
}
}
}
}
return classes;
}
When you run the code from within Eclipse it uses the compiled classes (by default in folder 'target'). However if you run the code from external normally you use a JAR file created by Eclipse.
And this problem arises when referencing something inside the JAR which is explained by the linked questions.
In short: URIs in the file system are syntactically correct. An URI referencing something into a JAR is no more a valid URI.

File.delete() fails to delete files in a directory

After writing the text files into a directory, i am trying to delete the empty files written by the PrintWriter.
File.delete() function fails to delete the file. Below is the code for writing and deleting.
private static void writeFile(ArrayList<ArrayList<String>> listRowVal, String szOutputDir, ArrayList<String> listHeader){
PrintWriter pw = null;
try {
ArrayList<String> listCells = listRowVal.get(0);
int iCells = listCells.size();
for(int k=0; k<iCells; k++){
String language = listHeader.get(k);
String szFileName = "files_"+ language +".csv";
pw = new PrintWriter(new FileWriter(szOutputDir + File.separator + szFileName));
for(ArrayList<String> listNCRCellVal : listRowVal){
String szVal = listNCRCellVal.get(k);
if(szVal != null && szVal.trim().length() > 0){
pw.println(szVal);
}
pw.flush();
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
try {
if(pw != null){
pw.close();
pw = null;
}
//System.gc();
deleteEmptyFiles(szOutputDir);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
private static void deleteEmptyFiles(String szDirPath) {
File file = new File(szDirPath);
if (file.isDirectory()) {
String[] files = file.list();
if (files.length > 0) {
for (String szFileName : files) {
File deleteFile = new File(szDirPath + File.separator + szFileName);
if (deleteFile.length() == 0) {
//deleteFile.setWritable(true, false);
boolean bdeleted = deleteFile.delete();
if(bdeleted){
System.out.println(deleteFile.getName() + " deleted.");
}
}
}
}
}
}
What is going wrong..??
You must close each PrintWriter, i.e. pw.close() must be on the end of "k" loop.

Categories

Resources