A friend of mine was having some issues with her project,she sent the files for me to debug. I am not sure but from the looks of it she doesn't use any ide, so when I got the files I made an Intellij project and copy pasted the files there.
When I ran the files on intellij it gave me a filenotfound exception, that was not been given in cmd.So I added the correct file path.
the file involves multithreading.
After that, I ran the file on intellij and it gave the desired output.
However, the file is giving a completely different output if I run it from cmd.
//This is the part from main where a thread is being made
Event e = new Restart(gc, 0, filename);
gc.addEvent(e);
new Thread(e).start();
In the restart class there is where the issue was:
public void getEvents(String filename) {
// open the file and read it using Scanner
try {
/** The file containing event details */
File myFile = new File(filename);
/** The Scanner object to read file */
Scanner myReader = new Scanner(myFile);
/** Current event being analyzed by Scanner */
String myEvent;
/** The delay with which the event will occur in ms */
long delayTime;
while ((myReader.hasNextLine())
&& ((myEvent = myReader.nextLine()) != null)) {
int equal = myEvent.indexOf('=');
int comma = myEvent.indexOf(',');
String className = myEvent.substring(equal+1, comma);
myEvent = myEvent.substring(comma+1);
Event e;
if (myEvent.contains("rings")) {
equal = myEvent.indexOf("=");
comma = myEvent.indexOf(",");
delayTime = Long.parseLong(myEvent.substring(equal+1, comma));
myEvent = myEvent.substring(comma+1);
equal = myEvent.indexOf("=");
int rings = Integer.parseInt(myEvent.substring(equal+1));
e = new Bell(delayTime);
gc.addEvent(e);
new Thread(e).start();
while(rings-- > 1) {
e = new Bell(delayTime += 2000);
gc.addEvent(e);
new Thread(e).start();
}
}
else {
equal = myEvent.indexOf("=");
delayTime = Long.parseLong(myEvent.substring(equal+1));
Class<Event> myClass = (Class<Event>)Class.forName("tme4." + className);
Constructor<Event> ctor = myClass.getConstructor(long.class);
e = ctor.newInstance(delayTime);
gc.addEvent(e);
new Thread(e).start();
}
}
myReader.close();
} catch (Exception e) {
e.printStackTrace();;
}
}
I only changed the first few lines:
From This:
File myFile = new File(filename);
/** The Scanner object to read file */
Scanner myReader = new Scanner(myFile);
Path currentPath = Paths.get(System.getProperty("user.dir"));
Path filePath = Paths.get(currentPath.toString(),filename);
To This:
filePath=Paths.get("C:\\Users\\Admin\\IdeaProjects\\summayah\\src\\examples1.txt");
System.out.println(filePath);
File myFile = new File(filename);
/** The Scanner object to read file */
Scanner myReader = new Scanner(myFile);
Can someone kindly help me? Thanks in advance
Related
public static void main(String[] args) throws FileNotFoundException {
File inputFile = null;
File outputFile = null;
if (args.length > 0) {
String inputName = args[0];
String outputName = args[1];
inputFile = new File(inputName);
outputFile = new File(outputName);
}else{
Scanner input = new Scanner(System.in);
inputFile = new File(input.next());
outputFile = new File(input.next());
}
}
this is my code and it's supposed to check the command line arguments for the file name but if there are none it will let the user type the names in. but how do I get it to throw the file not found exception?? i appreciate any help
You're better off using java.nio.file.Path over the older File class. java.nio.file.Files has a lot of utility methods for Paths.
You could check if the file exists then throw your own FileNotFoundException:
Path path = Path.of(filename);
if (!Files.exists(path)) throw new FileNotFoundException(path.toString());
Alternatively you could generate a NoSuchFileException:
path.getFileSystem().provider().checkAccess(path);
I get multiple errors when writing the header of a method that takes an array list and an integer as input.
I have tried several different ways of writing the header for the method. The body is good and gives me what I want but I can't get the header/call name (I don't know what you call the first line of a method) to not throw errors
/**
* Creates Arraylist "list" using prompt user for the input and output file path and sets the file name for the output file to
* p01-runs.txt
*
*/
Scanner scan = new Scanner(System.in);
System.out.println("Please enter the path to your source file: ");
String inPath = scan.nextLine(); // sets inPath to user supplied path
System.out.println("Please enter the path for your source file: ");
String outPath = scan.nextLine() + "p01-runs.txt"; // sets outPath to user supplied input path
ArrayList<Integer> listRunCount = new ArrayList<Integer>();
ArrayList<Integer> list = new ArrayList<Integer>();
/**
* Reads data from input file and populates array with integers.
*/
FileReader fileReader = new FileReader(inPath);
BufferedReader bufferedReader = new BufferedReader(fileReader);
// file writing buffer
PrintWriter printWriter = new PrintWriter(outPath);
System.out.println("Reading file...");
/**
* Reads lines from the file, removes spaces in the line converts the string to
* an integer and adds the integer to the array
*/
File file = new File(inPath);
Scanner in = new Scanner(file);
String temp=null;
while (in.hasNextLine()) {
temp = in.nextLine();
temp = temp.replaceAll("\\s","");
int num = Integer.parseInt(temp);
list.add(num);
}
listRunCount.findRuns(list, RUN_UP);
//********************************************************************************************************
public ArrayList<Integer> findRuns(ArrayList<Integer> list, int RUN_UP){
returns listRunCount;
}
error messages
Multiple markers at this line
- Syntax error on token "int", delete this token
- Syntax error, insert ";" to complete LocalVariableDeclarationStatement
- Integer cannot be resolved to a variable
- ArrayList cannot be resolved to a variable
- Syntax error, insert ";" to complete LocalVariableDeclarationStatement
- Illegal modifier for parameter findRuns; only final is permitted
- Syntax error, insert ") Expression" to complete CastExpression
- Syntax error on token "findRuns", = expected after this token
- Syntax error, insert "VariableDeclarators" to complete
LocalVariableDeclaration
- Syntax error, insert ";" to complete Statement
This sort of thing removes the need for statics. If you run your code from within the static method main() then all class methods, member variables, etc that are called or referenced from within main() must also be declared as static. By doing:
public class Main {
public static void main(String[] args) {
new Main().run();
}
}
eliminates the need for statics. In my opinion to properly do this the run() method within the class should also be passed the args[] parameter:
public class Main {
public static void main(String[] args) {
new Main().run(args);
}
private void run(String[] args) {
// You project code here
}
}
That way any Command Line arguments passed to the application can also be processed from within the run() method. You will find that most people won't use the method name run for this sort of thing since run() is a method name more related to the running of a Thread. A name like startApp() is more appropriate.
public class Main {
public static void main(String[] args) {
new Main().startApp(args);
}
private void startApp(String[] args) {
// You project code here
}
}
With all this in mind your code might look something like this:
public class Main {
public static void main(String[] args) {
new Main().run(args);
}
private void run(String[] args) {
String runCountFileCreated = createListRunCount();
if (!runCountFileCreated.equals("") {
System.out.println(The count file created was: " + runCountFileCreated);
}
else {
System.out.println(A count file was NOT created!);
}
}
/**
* Creates an ArrayList "list" using prompts for the input and output file
* paths and sets the file name for the output (destination) file to an
* incremental format of p01-runs.txt, p02-runs.txt, p03-runs.txt, etc. If
* p01 exists then the file name is incremented to p02, etc. The file name
* is incremented until it is determined that the file name does not exist.
*
* #return (String) The path and file name of the generated destination
* file.
*/
public String createListRunCount() {
String ls = System.lineSeparator();
File file = null;
Scanner scan = new Scanner(System.in);
// Get the source file path from User...
String sourceFile = "";
while (sourceFile.equals("")) {
System.out.print("Please enter the path to your source file." + ls
+ "Enter nothing to cancel this process:" + ls
+ "Source File Path: --> ");
sourceFile = scan.nextLine().trim(); // User Input
/* If nothing was entered (just the enter key was hit)
then exit this method. */
if (sourceFile.equals("")) {
System.out.println("Process CANCELED!");
return "";
}
// See if the supplied file exists...
file = new File(sourceFile);
if (!file.exists()) {
System.out.println("The supplied file Path/Name can not be found!." + ls
+ "[" + sourceFile + "]" + ls + "Please try again...");
sourceFile = "";
}
}
String destinationFile = "";
while (destinationFile.equals("")) {
System.out.print(ls + "Please enter the path to folder where data will be saved." + ls
+ "If the supplied folder path does not exist then an attempt" + ls
+ "will be made to automatically created it. DO NOT supply a" + ls
+ "file name. Enter nothing to cancel this process:" + ls
+ "Destination Folder Path: --> ");
String destinationPath = scan.nextLine();
if (destinationPath.equals("")) {
System.out.println("Process CANCELED!");
return "";
}
// Does supplied path exist. If not then create it...
File fldr = new File(destinationPath);
if (fldr.exists() && fldr.isDirectory()) {
/* Supplied folder exists. Now establish a new incremental file name.
Get the list of files already contained within this folder that
start with p and a number (ex: p01-..., p02--..., p03--..., etc)
*/
String[] files = fldr.list(); // Get a list of files in the supplied folder.
// Are there any files in the supplied folder?
if (files.length > 0) {
//Yes, so process them...
List<String> pFiles = new ArrayList<>();
for (String fileNameString : files) {
if (fileNameString.matches("^p\\d+\\-runs\\.txt$")) {
pFiles.add(fileNameString);
}
}
// Get the largest p file increment number
int largestPnumber = 0;
for (int i = 0; i < pFiles.size(); i++) {
int fileNumber = Integer.parseInt(pFiles.get(i).split("-")[0].replace("p", ""));
if (fileNumber > largestPnumber) {
largestPnumber = fileNumber;
}
}
largestPnumber++; // Increment the largest p file number by 1
// Create the new file name...
String fileName = String.format("p%02d-runs.txt", largestPnumber);
//Create the new destination File path and name string
destinationFile = fldr.getAbsolutePath() + "\\" + fileName;
}
else {
// No, so let's start with p01-runs.txt
destinationFile = fldr.getAbsolutePath() + "\\p01-runs.txt";
}
}
else {
// Supplied folder does not exist so create it.
// User Confirmation of folder creation...
JFrame iFrame = new JFrame();
iFrame.setAlwaysOnTop(true);
iFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
iFrame.setLocationRelativeTo(null);
int res = JOptionPane.showConfirmDialog(iFrame, "The supplied storage folder does not exist!"
+ ls + "Do you want to create it?", "Create Folder?", JOptionPane.YES_NO_OPTION);
iFrame.dispose();
if (res != 0) {
destinationFile = "";
continue;
}
try {
fldr.mkdirs();
}
catch (Exception ex) {
// Error in folder creation...
System.out.println(ls + "createListRunCount() Method Error! Unable to create path!" + ls
+ "[" + fldr.getAbsolutePath() + "]" + ls + "Please try again..." + ls);
destinationFile = "";
continue;
}
destinationFile = fldr.getAbsolutePath() + "\\p01-runs.txt";
}
}
ArrayList<Integer> list = new ArrayList<>();
/* Prepare for writing to the destination file.
Try With Resourses is use here to auto-close
the writer. */
try (PrintWriter printWriter = new PrintWriter(destinationFile)) {
System.out.println(ls + "Reading file...");
/**
* Reads lines from the file, removes spaces in the line converts
* the string to an integer and adds the integer to the List.
*/
String temp = null;
/* Prepare for writing to the destination file.
Try With Resourses is use here to auto-close
the reader. */
try (Scanner reader = new Scanner(file)) {
while (reader.hasNextLine()) {
temp = reader.nextLine().replaceAll("\\s+", "");
/* Make sure the line isn't blank and that the
line actually contains no alpha characters.
The regular expression: "\\d+" is used for
this with the String#matches() method. */
if (temp.equals("") || !temp.matches("\\d+")) {
continue;
}
int num = Integer.parseInt(temp);
list.add(num);
}
// PLACE YOUR WRITER PROCESSING CODE HERE
}
catch (FileNotFoundException ex) {
Logger.getLogger("createListRunCount() Method Error!").log(Level.SEVERE, null, ex);
}
}
catch (FileNotFoundException ex) {
Logger.getLogger("createListRunCount() Method Error!").log(Level.SEVERE, null, ex);
}
/* return the path and file name of the
destination file auto-created. */
return destinationFile;
}
}
I have a log file which is increasing always due to logging for different logging event in my application. Now i want to check some patterns in the log file and if I find any match for the patterns I will print it some where else. The log file is not static file it is always increasing and I my program should not check the old line again. It should always checks the new line which have not been checked yet.
Store the position of what you have checked up to in some kind of integer or file. now when you look for a pattern look for a regular expression and then print it to whatever output stream.
First read the file into an array like so, call the getWordsFromFile() method.
/**
*
* #param fileName is the path to the file or just the name if it is local
* #return the number of lines in fileName
*/
public static int getLengthOfFile(String fileName) {
int length = 0;
try {
File textFile = new File(fileName);
Scanner sc = new Scanner(textFile);
while (sc.hasNextLine()) {
sc.nextLine();
length++;
}
} catch (Exception e) {
}
return length;
}
/**
*
* #param fileName is the path to the file or just the name if it is local
* #return an array of Strings where each string is one line from the file
* fileName.
*/
public static String[] getWordsFromFile(String fileName) {
int lengthOfFile = getLengthOfFile(fileName);
String[] wordBank=new String[lengthOfFile];
int i = 0;
try {
File textFile = new File(fileName);
Scanner sc = new Scanner(textFile);
for (i = 0; i < lengthOfFile; i++) {
wordBank[i] = sc.nextLine();
}
return wordBank;
} catch (Exception e) {
System.err.println(e);
System.exit(55);
}
return null;
}
For larger files see this question
Then once you load your String[], you can iterate through like so.
for(int i=0;i<arr.length;i++)
doSomething(arr[i]);
to something like
for(int i= start;i<arr.length;i++)
doSomething(arr[i]);
What I have so far:
A block of code that intakes a username and password and write it to a textfile.
String usernameFilename;
usernameFilename = newUsernameField.getText();
char[] signupPassword = newPasswordField.getPassword();
String writePassword = new String(signupPassword);
try {
FileWriter userInfoWriter = new FileWriter(usernameFilename);
BufferedWriter writeToFile = new BufferedWriter(userInfoWriter);
writeToFile.write(usernameFilename);
writeToFile.write("\r\n" + writePassword);
writeToFile.close();
What I need to accomplish:
Create a directory to a pre-made folder called users.
Save the file to usernameFilename to a directory.
What I've tried:
I've searched online everywhere! I cant find anything to do this :c
Extra info:
Since all computers are different, I would like to use the .getAbsolutePath() method when creating the directory.
Take a look at:
java.io.File
File#exists
File#isDirectory
File#mkDirs
You could update your code to look more look this...
String usernameFilename;
usernameFilename = newUsernameField.getText();
char[] signupPassword = newPasswordField.getPassword();
String writePassword = new String(signupPassword);
File users = new File("users");
if ((users.exists() && users.isDirectory()) || users.mkdirs()) {
FileWriter userInfoWriter = null;
BufferedWriter writeToFile = null;
try {
userInfoWriter = new FileWriter(users.getPath() + File.seperator + usernameFilename);
writeToFile = new BufferedWriter(userInfoWriter);
writeToFile.write(usernameFilename);
writeToFile.newLine();
writeToFile.write(writePassword);
//....
} finally {
try {
writeToFile.close();
} catch (Exception exp) {
}
}
} else {
throw new IOException("Could not create/find Users directory");
}
Ok I need someone to clear things up for me.
I saw a hundred different ways of accessing a file to read in it (FileReader).
I tried all of them and can't find a way to do it correctly.
If I try :
String path = Engine.class.getResource("Words.txt").toString();
or
URL url = getClass().getResource("Words.txt");
String path = url.getFile();
File myFile = new File(path);
I go directly to :
dispatchUncaughtException
I just don't know where to look anymore since no one seems to agree on the good way to do it. Also, what is that kind of exception ?There must be an easy way to do this since it is such an easy task. I just want my program to see my Words.txt file that is in the SRC folder of my project.
Full code if it helps :
public String GetWord()
{
String [] Words = new String [10];
int random = (int)(Math.random() * 10);
URL url = getClass().getResource("Words.txt");
String path = url.getFile();
File myFile = new File(path);
try
{
FileReader myReader = new FileReader(myFile);
BufferedReader textReader = new BufferedReader(myReader);
for(int i = 0; i < 10; i++)
{
Words[i] = textReader.readLine();
}
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
return Words[random];
}
String path = Engine.class.getResource("Words.txt").toString();
For that to work, your file has to be in the same package as the Engine class. So, you probably want to move your file to the package where the class is at.
If you want to move the file into some other package then you need to specify the location starting from the root of the classpath. e.g. /some/other/pkg/Words.txt.
For a file which is not in the classpath, you need the full path along with the file name, to be able to read the file. The SRC folder itself is not a package and not in the classpath.
In that case, you can do something as follows:
FileInputStream fis = new FileInputStream("C:\\path\\to\\file\\Words.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(fis));
If you use Java 7 I recommend using newBufferedReader. It's more efficient and easier to use than the BufferedReader. I also modified your code to match the Java Code Conventions.
Working exmaple:
public String getWord() {
String[] words = new String[10];
int random = (int) (Math.random() * 10);
Path path = Paths.get("src" + System.getProperty("file.separator")
+ "Words.txt");
try {
BufferedReader textReader = Files.newBufferedReader(path,
StandardCharsets.UTF_8);
for (int i = 0; i < 10; i++) {
words[i] = textReader.readLine();
}
} catch (Exception e) {
System.out.println(e.getMessage());
}
return words[random];
}