I have this code that Reads a file from the file path given.
I have hardcoded F://dom.txt. I need the user to input that filepath instead.
How should i do it? Thanks
import java.io.BufferedReader;
import java.io.FileReader;
public class BuffReader extends Converter {
private static BufferedReader br() throws FileNotFoundException{
return new BufferedReader(new FileReader("F://dom.txt")); //<--filepath
}
static String strTem;
public static String readData(String Message){
try{
System.out.print(Message);
strTem = br().readLine();
}catch(Exception e){
System.err.println("Muling tingan ang iyong numerong ibinigay");
}
return strTem;
}
}
Well you need to give the filename to the oddly-named br() method. For example:
private static BufferedReader br(String path) throws FileNotFoundException {
return new BufferedReader(new FileReader(path));
}
public static String readData(String message){
try{
System.out.print(message);
strTem = br(message).readLine();
}catch(Exception e){
System.err.println("Muling tingan ang iyong numerong ibinigay");
}
return strTem;
}
That's assuming the parameter to readData is actually the file you want to read from... otherwise, you'll need to work out where you are going to get the file name from.
(It would be a good idea to work on exception handling and naming, by the way.)
Assuming you mean the input should come from the console (it could also be command line parameter or a gui or whatever you like really) then you should be able to use System.console().readLine("prompt for input")
(assuming it is a standalone) Change your main method to read the variable args[0].
public static void main (String[] args) {
readData(Message, args[0]);
}
Then change the method signatures for readData() and so on. Basically the above code tells you how to read a string from command line.
If you are asking in the middle of the program:
You can use
System.console().readLine("Enter file name: )
to get the user input.
Also i would suggest to keep this file in a config file and read it from the file in order for the program to be flexible.
Related
I have a batch file (test.bat) which has the command copy NUL test.txt. I have a java program, when i run it and when i enter a URL in the web browser e.g http://localhost:8080/runbatchfileparam, i get a result as either {"result":true} or {"result":false}. True means the java application has executed the batch file correctly (test.txt is created under the directory).
What i want to do now is, i want the java program to be able to take in parameters. E.g. User should be able to enter http://localhost:8080/runbatchfileparam/testabc.bat as the URL in web browser and the result should be {"result":true} if testabc.bat file is found and is executed (under desktop) and {"result":false} if the testabc.bat file is not found and not executed . (Note: All batch files are created under desktop filepath: C:/Users/attsuap1/Desktop)
I have edited my controller to take in a parameter and done the #PathVariable. In my codes, the fileName variable refers to the batch file name that i have created (test.bat, test123.bat) Command in test.bat: copy NUL test.txt Command in test123.bat: copy NUL test123.txt. However, i keep getting the result as {"result": false}. Which means the java program is not able to find the batch file and execute it.
Here are my codes:
RunBatchFile.java
public ResultFormat runBatch(String fileName) {
String var = fileName;
String filePath = "C:/Users/attsuap1/Desktop" + var;
try {
Process p = Runtime.getRuntime().exec(filePath);
int exitVal = p.waitFor();
return new ResultFormat(exitVal == 0);
} catch (Exception e) {
e.printStackTrace();
return new ResultFormat(false);
}
}
ResultFormat.java
private boolean result;
public ResultFormat(boolean result) {
this.result = result;
}
public boolean getResult() {
return result;
}
BatchFileController
private static final String template = "Sum, %s!";
#RequestMapping("/runbatchfileparam/{param}")
public ResultFormat runbatchFile(#PathVariable("param") String fileName ) {
RunBatchFile rbf = new RunBatchFile();
return rbf.runBatch(fileName);
}
Application.java
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
What do i have to edit or what should i add to the codes to achieve what i want?
After this line:
String filePath = "C:/Users/attsuap1/Desktop" + var;
Try to print the contents of filePath, i suspect that you come up with something like this:
C:/Users/attsuap1/Desktoptestabc.bat
I'm using html form to take input of a file and uploading it using doPost() method of HTTPservlet. [This part is done in package one] Now function from class Main.java to parse the uploaded file is called in this doPost method. This function resides in the other package. [Moving to the other package-> ] Here the class Main.java calls Integrated.java which has all the instances of class and functions needed to be called in order to parse the file that was uploaded. (I have separate classes for extracting data, chunking, sorting and generating csv out of the data parsed)
After I parse the file, I put values in variables which are initialized in the last file CSVgenerator.java. Values to these variables are added before in the class SortAndOutput.java. To test that I'm getting the right values in my class, I print the variables right before I call the functions writingDatabase() and writingTraining(). These two functions save the values of the variables in CSV files.
I'm using OpenCSV for writing the files. Using apache Tika for extraction of data and lingpipe to parse.
THE BIG PROBLEM:
I (intentionally) write main func in CSVgenerator.java and test it. Both the files are written properly. The missing value columns are left blank. PERFECT! (If i have any of the CSV open separately, it raises an exception like it should)
But when i comment out the main func and run the whole project together on server, the CSVs are not written. Even if the files are opened separately(outside eclipse), it doesn't give an error.
I have tested the whole integrated Java code by putting a main method in Main.java and it runs perfectly. The problem occurs when servlet is run/I run project on server.
I don't know if other files will be helpful or not, I'm posting the hierarchy and CSVgenerator class
Workspace Screenshot
CSVGenerator.java
package com.fypv1.parser;
import java.io.*;
import java.util.*;
import com.opencsv.*;
public class CSVgenerator {
public static String CGPAinitial="-";
public static String universityNameOut="-";
public static String emailIDOut="-";
public static String phoneNoOut="-";
public static String phpKnow="NO";
public static String databaseKnow="NO";
public static String jsKnow="NO";
public static String bootStrapKnow="NO";
public static String aspKnow="NO";
public static String htmlKnow="NO";
public static String cssKnow="NO";
public static String jqueryKnow="NO";
public static String jspKnow="NO";
public static String reactjsKnow="NO";
public static String ajaxKnow="NO";
public static String oopKnow="NO";
public static String javaKnow="NO";
public static String androidKnow="NO";
private int idNumber;
Writer wr;
Scanner scanner;
/*
* public static void main(String[] args) throws IOException {
new CSVgenerator();
}
*/
//DEFAULT CLASS CONSTRUCTOR
CSVgenerator() throws IOException
{
String trainingCSV = "TrainingData.csv";
String databaseCSV = "databaseInfo.csv";
String idNumberFile = "idnum.txt";
try {
scanner = new Scanner(new File(idNumberFile));
SortAndOutput.applicantIDnumber=scanner.nextInt();
idNumber=SortAndOutput.applicantIDnumber;
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
System.out.println("IDnumberFileUnavailable");
}
try {
wr = new FileWriter(idNumberFile);
int newIDNumber=idNumber+1;
wr.write(newIDNumber+"");
wr.close();
} catch (IOException e1) {
//
e1.printStackTrace();
}
//System.out.println( String.valueOf(idNumber)+"+"+universityNameOut+"+"+CGPAinitial+"+"+emailIDOut+"+"+ phoneNoOut+"+"+CGPAinitial+"+"+phpKnow+"+"+ databaseKnow+"+"+ jsKnow+"+"+ bootStrapKnow+"+"+ aspKnow+"+"+ htmlKnow+"+"+ cssKnow+"+"+ jqueryKnow+"+"+ jspKnow+"+"+ reactjsKnow+"+"+ ajaxKnow+"+"+ "?");
writingDatabase(databaseCSV);
writingTraining(trainingCSV);
}//CONSTRUCTOR ENDS
void writingDatabase(String databaseCSV) throws IOException {
CSVWriter dbWriter;
String [] record1={String.valueOf(idNumber),universityNameOut,CGPAinitial,emailIDOut, phoneNoOut };
dbWriter= new CSVWriter(new FileWriter(databaseCSV, true));
dbWriter.writeNext(record1);
dbWriter.close();
}
void writingTraining(String trainingCSV) throws IOException {
CSVWriter trainingWriter;
String [] record={String.valueOf(idNumber),CGPAinitial,phpKnow, databaseKnow, jsKnow, bootStrapKnow, aspKnow, htmlKnow, cssKnow, jqueryKnow, jspKnow, reactjsKnow, ajaxKnow, "?"};
trainingWriter = new CSVWriter(new FileWriter(trainingCSV, true));
trainingWriter.writeNext(record);
trainingWriter.close();
}
}
Integrated.java
ResumeUploadService.java (the servlet)
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
try {
Part file = request.getPart("file");
resumeFileName = Paths.get(file.getSubmittedFileName()).getFileName().toString();
file.write(path + resumeFileName);
printOnClient(response, "Upload Successful!");
}
catch (Exception e) {
printOnClient(response, "Upload Failed!");
}
new Main(path,resumeFileName);
}
Please let me know if more code is needed to debug this.
It was updating files both times. When it ran on server, it created files in eclipse folder and when i ran as java application, it updated files in project folder
Your files are written in the application folder unless otherwise specified. This is the relative path to the running application.
Just because you tested the application in Eclipse doesn't mean that the server deployment would write to the same folder.
Ideally, you can specify a configuration parameter to your Servlet for an absolute path where files are to be stored
Error in code:
If that train is removed then also show compiler error as below. I tried a lot to remove that and classify sentence as positive or negative.
An InputStreamFactory in not the same as an InputStream. Here is a simple bit of code that will create an InputStreamFactory for you. (You might say it is an InputStreamFactoryFactory :-) )
public static InputStreamFactory getInputStreamFactory(final File file) throws IOException{
return new InputStreamFactory() {
#Override
public InputStream createInputStream() throws IOException {
return new FileInputStream(file);
}
};
}
see javadocs: https://opennlp.apache.org/documentation/1.7.2/apidocs/opennlp-tools/opennlp/tools/util/InputStreamFactory.html
I'm trying to print out the usernames of a certain program into a file but PrintWriter is not printing anything on my file. I've tried everything mentioned on stackOverFlow none of them worked.
Users Class
private File usersListFile;
private PrintWriter usersListPrintWriter;
private Scanner usersListScanner;
Constructor:
Users(){
try {
this.usersListFile = new File("D:\\Dairy\\usersList.txt");
if(usersListFile.exists()){
this.usersListPrintWriter = new PrintWriter(new BufferedWriter(new FileWriter("D:\\Dairy\\usersList.txt", true)));
this.usersListScanner = new Scanner("D:\\Dairy\\usersList.txt");
}
else
System.err.println("File does not exist !");
}
catch(Exception e){
System.err.println("Error: Users Class!");
}
}
Method:
public void addToUsersList(String username){
usersListPrintWriter.print(username);
}
Main Method:
public static void main(String[] args) {
Users usersObject = new Users();
usersObject.addToUsersList("USERNAME");
}
usersListPrintWriter is buffered, so you need to flush the data (as Alexandro mentioned too).
You also likely will need to change the print into a println so newly added users are output on separate lines.
Your Scanner will not work, since you're scanning the given string, not the file content. Use new Scanner(this.usersListFile) instead.
You should also re-use your File object on the previous line: new FileWriter(this.usersListFile, true)
And I would say that having a Writer and a Scanner open on the same file at the same time is a bad idea, if it even works. You should probably just load all the users into memory and close the scanner before opening the writer, unless you have
public void addToUsersList(String username){
usersListPrintWriter.print(username);
usersListPrintWriter.flush();
}
Then, when you don't need anymore your printwriter, call close().
I've write a Java programm and packaged it the usual way in a jar-File - unfortunately is needs to read in a txt-File. Thats way the programm failed to start on other computer machines because it could not find the txt-file.
At the same time Im using many images in my programm but here there is no such problem: I "copy" the images to the eclipse home directory, so that they are packaged in the jar-File and usable through following command:
BufferedImage buffImage=ImageIO.read(ClassName.class.getClassLoader()
.getResourceAsStream("your/class/pathName/));
There is something similar for simple textfiles which then can be use as a normal new File()?
Edit
Ive try to solve my problem with this solution:
package footballQuestioner;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import javax.security.auth.login.Configuration;
public class attempter {
public static void main(String[] args) {
example ex = new example();
}
}
class example {
public example() {
String line = null;
BufferedReader buff = new BufferedReader(new InputStreamReader(
Configuration.class
.getResourceAsStream("footballQuestioner/BackUpFile")));
do {
try {
line = buff.readLine();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} while (line != null);
}
}
But it gives always an NullPointerException...do I have forgotten something?
Here is as required my file structure of my jar-File:
You can load the file from the ClassPath by doing something like this:
ClassLoader cl = getClass().getClassLoader()
cl.getResourceAsStream("TextFile.txt");
this should also work:
getClass().getResourceAsStream(fileName);
File always points to a file in the filesystem, so I think you will have to deal with a stream.
There are no "files" in a jar but you can get your text file as a resource (URL) or as an InputStream. An InputStream can be passed into a Scanner which can help you read your file.
You state:
But it gives always an NullPointerException...do I have forgotten something?
It means that likely your resource path, "footballQuestioner/BackUpFile" is wrong. You need to start looking for the resource relative to your class files. You need to make sure to spell your file name and its extension correctly. Are you missing a .txt extension here?
Edit
What if you try simply:
BufferedReader buff = new BufferedReader(new InputStreamReader(
Configuration.class.getResourceAsStream("BackUpFile")));