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
Related
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();
}
I want to read out a file on a seperate thread and after that I want to move the file to a new directory but the compiler keeps telling me that I can't move the file because it is used by another process. I have checked it multiple times and my readers are closed and I used the join() function to wait until the readThread has finished what could this be?
public class CallLogReader extends Thread {
private Path path;
private LinkedList<CallLog> callLogs;
public CallLogReader(Path path){
setPath(path);
callLogs = new LinkedList<>();
}
public Path getPath() {
return path;
}
public void setPath(Path path) {
this.path = path;
}
public LinkedList<CallLog> getCallLogs() {
return callLogs;
}
#Override
public void run(){
FileReader reader = null;
BufferedReader buffReader = null;
try{
reader = new FileReader(path.toFile());
buffReader = new BufferedReader(reader);
String currentLine = buffReader.readLine();
while(currentLine != null){
String[] dataBlocks = currentLine.split(";");
if(!dataBlocks[7].equals("IGNORE")){
callLogs.add(new CallLog(Integer.parseInt(dataBlocks[0]) ,dataBlocks[1], ConvertStringToDate(dataBlocks[2], dataBlocks[3]), dataBlocks[4], dataBlocks[5], Integer.parseInt(dataBlocks[6]), dataBlocks[7]));
}
currentLine = buffReader.readLine();
}
}
catch(IOException ex){
System.out.println(ex.getMessage());
}
finally{
try{
if(buffReader != null){
buffReader.close();
}
if(reader != null){
reader.close();
}
}
catch(IOException ex){
System.out.println(ex.getMessage());
}
}
}
private LocalDateTime ConvertStringToDate(String dateString,String timeString){
String dateTimeString = dateString + " " + timeString;
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd/MM/yyyy HH:mm:ss");
return LocalDateTime.parse(dateTimeString,formatter);
}
public void moveFile(){
Path newPath = Paths.get(path.getParent().getParent().toString() + "\\processed\\" + path.getFileName());
try{
Files.move(path,newPath,StandardCopyOption.REPLACE_EXISTING);
}
catch(IOException ex){
System.out.println(ex.getMessage());
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Path path_1 = Paths.get("C:\\Users\\11601037\\Desktop\\resources\\in\\testdata1.csv");
CallLogReader reader_1 = new CallLogReader(path_1);
reader_1.run();
try{
reader_1.join();
}
catch(InterruptedException ex){
System.out.println(ex.getMessage());;
}
reader_1.moveFile();
System.out.println(path_1.getParent().getParent().toString());
}
}
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");
}
I'm trying to print '1' or '0' in text view if it passes the if statements. I ran it in the debug mode, and it all works, but it is not printing in the text view. How do I fix this I tried a lot of stuff, but I'm still stuck.
public class Readcsv {
private static final String FILE_DIR = "/Users/Me/Downloads";
private static final String FILE_TEXT_NAME = ".csv";
public static void main(String [] args) throws Exception{
PrintWriter writer = new PrintWriter("/users/Me/Documents/Test.txt", "UTF-8");
int i=-1;
BufferedReader br = null;
String line = "";
String cvsSplitBy = ",";
//Find Number of Files
String[] list = new Readcsv().FileCount(FILE_DIR, FILE_TEXT_NAME);
System.out.println("Total Files = " + list.length);
while(i++ < list.length){
System.out.println("Loop Count = " + i);
try {
br = new BufferedReader(new FileReader("/users/Tanuj/Downloads/" + list[i]));
while ((line = br.readLine()) != null) {
// use comma as separator
String[] strRecord = line.split(cvsSplitBy);
if (!strRecord[0].equals("timestampMs")){
int c = Integer.parseInt(strRecord[4]);
int e = Integer.parseInt(strRecord[5]);
if(c>e){
writer.print("1");
}
else{
writer.print("0");
}
break;
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
} //End of while
writer.close();
} //End of Main
public String[] FileCount(String folder, String ext) {
GenericExtFilter filter = new GenericExtFilter(ext);
File dir = new File(folder);
if(dir.isDirectory()==false){
System.out.println("Directory does not exists : " + FILE_DIR);
return null;
}
// list out all the file name and filter by the extension
String[] list = dir.list((FilenameFilter) filter);
return list;
}
// inner class, generic extension filter
public class GenericExtFilter implements FilenameFilter {
private String ext;
public GenericExtFilter(String ext) {
this.ext = ext;
}
public boolean accept(File dir, String name) {
return (name.endsWith(ext));
}
}
}
have you tryed BufferedWriter?
File file = new File("Test.txt");
FileOutputStream fos = new FileOutputStream(file);
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(fos));
bw.write("something");
bw.newLine();
bw.close();
I'm trying to extract the files in an .iso file I have. There are no errors and the console prints out all the files inside. However, none of the files get extracted. Any help is greatly appreciated!
I was able to find this link but I can't seem to integrate it in to my project.
Link to code example
class DownloadWorker extends SwingWorker<String, Object> {
private String flocation;
private JLabel out;
public DownloadWorker(String location, JLabel fout)
{
this.flocation = location;
this.out = fout;
}
#Override
public String doInBackground() {
//download here
out.setText("Beginning download. This may take a few minutes.");
try {
//ProgressBar/Install
System.out.println("FILELOCATION:\n----------");
System.out.println(flocation);
String URL_LOCATION = "http://www.futureretrogaming.tk/gamefiles/ProfessorPhys.iso";
String LOCAL_FILE = (flocation + "\\ProfessorPhys\\");
File localfile = new File(LOCAL_FILE);
if (localfile.exists()) {
System.out.println("Directory exists!");
}
else {
System.out.println("Directory doesn't exist! Creating...");
localfile.mkdir();
if (localfile.exists())
System.out.println("Directory created!");
}
System.out.println("LOCALFILE:\n-------");
System.out.println(LOCAL_FILE);
URL website = new URL(URL_LOCATION);
ReadableByteChannel rbc = Channels.newChannel(website.openStream());
FileOutputStream fos = new FileOutputStream(LOCAL_FILE+"\\ProfessorPhys.iso\\");
fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
System.out.println("--------\nDone Downloading\n---------");
RandomAccessFile randomAccessFile = null;
ISevenZipInArchive inArchive = null;
try {
randomAccessFile = new RandomAccessFile(localfile +"\\ProfessorPhys.iso\\", "r");
inArchive = SevenZip.openInArchive(null, // autodetect archive type
new RandomAccessFileInStream(randomAccessFile));
// Getting simple interface of the archive inArchive
ISimpleInArchive simpleInArchive = inArchive.getSimpleInterface();
System.out.println(" Hash | Size | Filename");
System.out.println("----------+------------+---------");
for (ISimpleInArchiveItem item : simpleInArchive.getArchiveItems()) {
final int[] hash = new int[] { 0 };
if (!item.isFolder()) {
ExtractOperationResult result;
final long[] sizeArray = new long[1];
result = item.extractSlow(new ISequentialOutStream() {
public int write(byte[] data) throws SevenZipException {
hash[0] ^= Arrays.hashCode(data); // Consume data
sizeArray[0] += data.length;
return data.length; // Return amount of consumed data
}
});
if (result == ExtractOperationResult.OK) {
System.out.println(String.format("%9X | %10s | %s", //
hash[0], sizeArray[0], item.getPath()));
} else {
System.err.println("Error extracting item: " + result);
}
}
}
} catch (Exception e) {
System.err.println("Error occurs: " + e);
System.exit(1);
} finally {
if (inArchive != null) {
try {
inArchive.close();
} catch (SevenZipException e) {
System.err.println("Error closing archive: " + e);
}
}
if (randomAccessFile != null) {
try {
randomAccessFile.close();
} catch (IOException e) {
System.err.println("Error closing file: " + e);
}
}
}
} catch (Exception e) {
System.out.println(e);
}
return "done";
}
#Override
protected void done() {
//done
out.setText(out.getText() + "\n Operation Done");
}
}
Code I'm trying to implement:
public class ExtractorUtil {
private static Logger logger = Logger.getLogger(ExtractorUtil.class.getCanonicalName());
public static void extract(File file, String extractPath) throws Exception {
ISevenZipInArchive inArchive = null;
RandomAccessFile randomAccessFile = null;
randomAccessFile = new RandomAccessFile(file, "r");
inArchive = SevenZip.openInArchive(null, new RandomAccessFileInStream(randomAccessFile));
inArchive.extract(null, false, new MyExtractCallback(inArchive, extractPath));
if (inArchive != null) {
inArchive.close();
}
if (randomAccessFile != null) {
randomAccessFile.close();
}
}
public static class MyExtractCallback implements IArchiveExtractCallback {
private final ISevenZipInArchive inArchive;
private final String extractPath;
public MyExtractCallback(ISevenZipInArchive inArchive, String extractPath) {
this.inArchive = inArchive;
this.extractPath = extractPath;
}
#Override
public ISequentialOutStream getStream(final int index, ExtractAskMode extractAskMode) throws SevenZipException {
return new ISequentialOutStream() {
#Override
public int write(byte[] data) throws SevenZipException {
String filePath = inArchive.getStringProperty(index, PropID.PATH);
FileOutputStream fos = null;
try {
File dir = new File(extractPath);
File path = new File(extractPath + filePath);
if (!dir.exists()) {
dir.mkdirs();
}
if (!path.exists()) {
path.createNewFile();
}
fos = new FileOutputStream(path, true);
fos.write(data);
} catch (IOException e) {
logger.severe(e.getLocalizedMessage());
} finally {
try {
if (fos != null) {
fos.flush();
fos.close();
}
} catch (IOException e) {
logger.severe(e.getLocalizedMessage());
}
}
return data.length;
}
};
}