Cannot Open .txt file to read integers - java

i am having an issue opening a file and getting my program to read the integers in the file. In the code below, to get my car data i can either have it randomly generated to get my duration time for a car, and the chance that a car arrives. Or read integers from a file. The file is already given by our professor and her is what is in the file:
37259 9819
46363 22666
46161 79934
5693 31416
91459 8272
72792 9493
83603 8372
77842 64629
84792 747
1299 178
Apparently I am unable to open the file even using the absolute path, or data = dataFile.nextInt() isn't the correct format to use. Any help would be appreciated i am absolutely stumped on this part, my whole program works but files are my Achilles heel.
if (dataSource == 1) {
System.out.printf("Enter a filename \t :");
String aName = input.next();
java.io.File file = new java.io.File(aName);
try {
dataFile = new Scanner(file);
} catch (Exception e) {
System.out.println("Can't open file");
}
} else {
dataRandom = new Random();
System.out.println("Is Random Active");
}
input.close();
}
private void getCarData() {
if (dataSource == 1) {
int data1;
int data2;
data1 = dataFile.nextInt();
data2 = dataFile.nextInt();
anyNewArrival = (((data1%100) + 1) <= chancesOfArrival);
serviceDuration = (data2%maxDuration) + 1;
System.out.println("New Car has arrived with Duration Time: " + serviceDuration);//}
}

If running from Netbeans or Ecplise, you can use the relative path "text.txt" And make sure your file structure is something like this
ProjectRoot
src
build
text.txt

Related

How to write a method that increments a file name in java

I am writing a method that takes a a string of html and writes it to a file. The method should increment the file name if the file already exists. For example, if wordmatch.html already exists then a new file should be created wordmatch1.html so and so fourth.
I have created a method that writes the html to a file. I'm working on the last part to incrementally change the name of a new file if the file already existst.
public void saveContent(WordMatch wordMatch){
logger.info(wordMatch);
try {
File file = new File("wordmatch0.html");
String html = wordMatch.toString();
String cleanedHTML = html.replace("WordMatch(content=","").replace(")","");
logger.info(cleanedHTML);
if (file.createNewFile()) {
System.out.println("File created: " + file.getName());
try {
FileWriter myWriter = new FileWriter("word_match.html");
myWriter.write(cleanedHTML);
myWriter.close();
System.out.println("Successfully wrote to the file.");
} catch (IOException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
} else {
String fileName = file.getName().toString();
String index = fileName.substring(fileName.indexOf("h") + 1);
index = index.substring(0, index.indexOf("."));
Integer parsedInt = Integer.parseInt(index);
System.out.println(parsedInt);
parsedInt+=1;
fileName = fileName.replace(index,parsedInt.toString());
System.out.println(fileName);
System.out.println("fileName should have been printed by now");
file = new File(fileName);
FileWriter myWriter = new FileWriter(file);
myWriter.write(cleanedHTML);
myWriter.close();
//TODO add method to write file name with new index
System.out.println("File already exists.");
}
} catch (IOException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
}
Any help with this would be greatly appreciated. Thanks.
A simple approach will be count the number of files matching your file name and then increment the numberOfFiles to create a new file name :
Stream<Path> files = Files.list(Paths.get("C:\\your\\local\\path"));
long numberOfFiles = files.map(Path.class::cast)
.filter(path -> path.getFileName().toString().startsWith("wordmatch"))
.count();
After all you have to manage certains situations, to have a good algorithm for managing your files.
A problem that seems trivial but has so many pitfalls.
The algorithm you wrote won't work for the following reasons:
Simple if-else is not enough, you need to go through a loop to find the last index, because potentially there could be many files created already.
Else block tries to find an index from the file name that should't have one.
Moreover, there are additional questions that may raise.
What if someone deleted the intermediate indexes and now you have 1 and 4, do you want to go with 2 or 5?
Can someone delete the files from the directory except the programm?
Are nested directories possible?
How often files are created?
Can someone manually create a file with a proper name bypassing the programm?
And more importand question is - do you really want to stick to the strict brute-force counter on the actual files listed in a directory?
If the answer is yes, the more reasonable would be to check the files using File.list(), sort them, take the last index and increment them instead of trying to create a file and increment on a failure.
public class Main {
public static void main(String[] args) {
File directoryPath = new File("path_to_your_dir");
FilenameFilter filenameFilter = (dir, name) -> !dir.isFile();
Integer maxIndex = Arrays.stream(directoryPath.list(filenameFilter))
// Take numeric index from the end of the file name, beware of file extensions!
.map(name -> name.substring("word_match".length(), name.lastIndexOf('.')))
.map(Main::parseOrDefault) // Parse it to a number
.max(Integer::compareTo) // Define how to compare them
.orElse(-1);
// -1 is no files, 0 if a file with no index, otherwise max index
System.out.println(maxIndex);
}
private static Integer parseOrDefault(String integer) {
try {
return Integer.valueOf(integer);
} catch (NumberFormatException e) {
return 0;
}
}
}
If the answer is no, you can have a counter that is persisted somewhere (file system, BD) and incremented regardless every time.
And more simple approach is establish a frequence of file creations and simply append a timestamp/date-time to the end of each file.

How two find unique difference between to files in Java and print their line numbers?

I have to text files and I want to print the line numbers where the contents of the second file is modified?
file 1:
1/ hi
2/
3/
4/ start
5/ {
6/
7/ while(){
8/ }
9/ }
file 2:
1/ hi
2/
3/
4/
5/ start
6/
7/
8/ {
9/ if(
10/ while(){
11/ }
12/ }.
The output should be: 9 (as an extra if is added in the file 2). Note, there might be unnecessary tabs and newlines.Can anyone help me with this problem?
import java.util.Scanner;
//convert a file into a file_simple form
File simplified(String src , String srcPath , String name) throws FileNotFoundException{
File fileSrc = new File(src);
File fileDest = new File(srcPath + "\\" + name + "_simple");
Scanner scSrc = new Scanner(fileSrc);
PrintWriter pw = new PrintWriter(fileDest);
while(scSrc.hasNextLine()) {
String take = scSrc.nextLine();
if(take.equals("")) {
continue;
}
String take1 = take.trim();
pw.println(take1);
}
pw.close();
scSrc.close();
return fileDest;
}
//write what difference the second file has
void differenceInTwoFiles(File file1 , File file2 , String logPath , String UserName) throws FileNotFoundException {
File file1Simple = simplified(file1.getAbsolutePath() , file1.getParentFile().getAbsolutePath() , file1.getName());
File file2Simple = simplified(file2.getAbsolutePath() , file2.getParentFile().getAbsolutePath() , file2.getName());
System.out.println(file2.getAbsolutePath() +" " + file2.getParentFile().getAbsolutePath() +" "+ file2.getName());
File log = new File(logPath);
PrintWriter pwLog = new PrintWriter(log);
Scanner scF1 = new Scanner(file1Simple);
Scanner scF2 = new Scanner(file2Simple);
while(scF1.hasNextLine() && scF2.hasNextLine()) {
String first = scF1.nextLine();
String second = scF2.nextLine();
if(!first.equals(second)) {
pwLog.println(UserName + " has MODIFIED in " + file2.getName() + " : " + second);
}
}
pwLog.close();
scF1.close();
scF2.close();
}
}
I vote for not using Java to handle this task, because there are already very good tools out there for doing along the lines of what you want. For example, Linux has a diff tool which might work well here:
diff file1.txt file2.txt
At the very least, the output from diff would flag every line which were in disagreement between the two files, and maybe just that would be enough to meet your requirements.

Problems with duplicate filenames when creating via widget

I've got a widget that allows the user to drag and drop an email message or a file into the widget to copy it to their file system. It's the FileExplorer project in OpenNTF, designed by people far more experienced than I am. I want to modify it to provide a new filename if the current filename already exists in the location they're dropping it on. With emails I'd hoped to be able to grab the sender and date, but I've been throwing errors when I try to access the file contents during a drag-and-drop of email.
So, my issue is actually simple. I've got the 'if' to determine if the filename is taken, but I'm overwhelmed trying to figure out how to test multiple options for the filename (like numbering then 'file1.eml', 'file2.eml', 'file3.eml'). I tried, below, inserting the word DUPLICATE, but I'm having no joy.
try {
if (source.isDirectory()) {
File dirTarget = new File(fDest.getAbsoluteFile() + File.separator + source.getName());
if (!dirTarget.exists()) {
dirTarget.mkdir();
}
copyDir(monitor, source, dirTarget);
}
if (source.isFile()) {
File dest = new File(fDest.getAbsolutePath() + File.separator + source.getName());
if (dest.getAbsolutePath().compareTo(source.getAbsolutePath()) != 0) {
copyFile(monitor, source, dest);
} else {
dest = new File(fDest.getAbsolutePath() + File.separator + "DUPLICATE" + File.separator + source.getName());
copyFile(monitor, source, dest);
}
}
} catch (IOException e) {
}
For reference, the copyFile method's parameters are
private void copyFile(IProgressMonitor monitor, File fSource, File fTarget) throws IOException
You need to construct your file name different.
File.seperator
results in / \ or : depending on your platform since it is the char separating the directory from the file.
Since you are dropping a file, you don't need check for the directory, up to you. You need a loop to test file names. To make it easy use (DUPLICATE 1) (DUPLICATE 2) etc. Something like this:
private final static String DUPLICATE = "DUPLICATE";
private void copyOut(File source, File fDest, Monitor monitor) {
try {
if (!source.exists() || !fDest.exists()) {
// one or two files missing, can't copy
// handle error here!
} else {
String destName = fDest.getAbsolutePath()+ File.separator + source.getName();
File dest = new File(destName);
if (source.isDirectory()) {
if (!dest.exists()) {
destPath.mkdirs(); // Fix missing
} else if (dest.isFile()) {
// Raise an error. Destination exists as file source is directory!!!
}
} else { // We checked for existence and dir, so it is a file
// Don't overwrite an existing file
dest = this.checkforDuplicate(dest);
}
copyFile(monitor, source, dest);
}
} catch (IOException e) {
// Error handling missing here!
}
}
private File checkforDuplicate(File dest) {
if (!dest.exists()) {
return dest;
}
int duplicateNum = 1;
while (true) {
ArrayList<String> pieces = Arrays.asList(dest.getAbsolutePath().split("."));
pieces.add(pieces.size()-1, DUPLICATE);
if (duplicateNum > 1) {
pieces.add(pieces.size()-1,Integer.toString(duplicateNum));
}
duplicateNum++;
StringBuilder newName = newStringBuilder();
for (String s : pieces) {
newName.append(s);
newName.append(".");
}
// Strip the last .
String outName = newName.substring(0, newName.length()-2);
File result = new File(outName);
if (!result.exists()) {
return result;
}
}
}
Check the code, written off memory, will contain typos. also doesn't deal with file names that don't contain a dot.

Generating a text file of the output through Java IO [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Reading the java files from the folder
I have developed a java code that reads files from the folder chosen by the user. It displays how many lines of code are in each file, it reads only .java filesonly and final outcome is shown on console , I was thinking that output to be get displayed on console but along with a text file conataing the same information to be get stored on desktop also, please advise how to that and the name of the file that is generated its name is to be based on timestamp lets assume that name of the output file would be 'output06282012' and that text file should contain the same information that is shown on the console , here is my piece of code...
public static void main(String[] args) throws FileNotFoundException {
JFileChooser chooser = new JFileChooser();
chooser.setCurrentDirectory(new java.io.File("C:" + File.separator));
chooser.setDialogTitle("FILES ALONG WITH LINE NUMBERS");
chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
chooser.setAcceptAllFileFilterUsed(false);
if (chooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION)
{ Map<String, Integer> result = new HashMap<String, Integer>();
File directory = new File(chooser.getSelectedFile().getAbsolutePath());
int totalLineCount = 0;
File[] files = directory.listFiles(new FilenameFilter(){
#Override
public boolean accept(File directory, String name) {
if(name.endsWith(".java"))
return true;
else
return false;
}
}
);
for (File file : files)
{
if (file.isFile())
{ Scanner scanner = new Scanner(new FileReader(file));
int lineCount = 0;
try
{ for (lineCount = 0; scanner.nextLine() != null; lineCount++) ;
} catch (NoSuchElementException e)
{ result.put(file.getName(), lineCount);
totalLineCount += lineCount;
}
} }
System.out.println("*****************************************");
System.out.println("FILE NAME FOLLOWED BY LOC");
System.out.println("*****************************************");
for (Map.Entry<String, Integer> entry : result.entrySet())
{ System.out.println(entry.getKey() + " ==> " + entry.getValue());
}
System.out.println("*****************************************");
System.out.println("SUM OF FILES SCANNED ==>"+"\t"+result.size());
System.out.println("SUM OF ALL THE LINES ==>"+"\t"+ totalLineCount);
}
}
output that is displayed on console is to be stored in a text file on desktop also, please advise how to that and the name of the file that is generated its name is to be based on timestamp lets assume that name of the output file would be 'output06282012' and that text file should contain the same information that is shown on the console
I'd advice you to ask questions more precisely. From what I understand from your question, you want to write some information to a text file. To do this all you have to do is this -
try{
java.util.Date date= new java.util.Date();
System.out.println(new Timestamp(date.getTime()));
BufferedWriter out = new BufferedWriter(new FileWriter("C://Desktop//output"+new Timestamp(date.getTime())+".txt"));
out.write("some information");
out.close;
}catch(IOException e){
e.printStackTrace();
}
So in your code inplace of System.out.println(); statements you can use out.write()
statements to write to a text file.
Hope this helps you.

Generating the output file through java IO

I have developed a java code that reads files from the folder chosen by the user. It displays how many lines of code are in each file, it reads only .java filesonly and final outcome is shown on console , I was thinking that output to be get displayed on console but along with a text file conataing the same information to be get stored on desktop also, please advise how to that and the name of the file that is generated its name is to be based on timestamp lets assume that name of the output file would be 'output06282012' and that text file should contain the same information that is shown on the console , here is my piece of code...
public static void main(String[] args) throws FileNotFoundException {
JFileChooser chooser = new JFileChooser();
chooser.setCurrentDirectory(new java.io.File("C:" + File.separator));
chooser.setDialogTitle("FILES ALONG WITH LINE NUMBERS");
chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
chooser.setAcceptAllFileFilterUsed(false);
if (chooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION)
{ Map<String, Integer> result = new HashMap<String, Integer>();
File directory = new File(chooser.getSelectedFile().getAbsolutePath());
int totalLineCount = 0;
File[] files = directory.listFiles(new FilenameFilter(){
#Override
public boolean accept(File directory, String name) {
if(name.endsWith(".java"))
return true;
else
return false;
}
}
);
for (File file : files)
{
if (file.isFile())
{ Scanner scanner = new Scanner(new FileReader(file));
int lineCount = 0;
try
{ for (lineCount = 0; scanner.nextLine() != null; lineCount++) ;
} catch (NoSuchElementException e)
{ result.put(file.getName(), lineCount);
totalLineCount += lineCount;
}
} }
System.out.println("*****************************************");
System.out.println("FILE NAME FOLLOWED BY LOC");
System.out.println("*****************************************");
for (Map.Entry<String, Integer> entry : result.entrySet())
{ System.out.println(entry.getKey() + " ==> " + entry.getValue());
}
System.out.println("*****************************************");
System.out.println("SUM OF FILES SCANNED ==>"+"\t"+result.size());
System.out.println("SUM OF ALL THE LINES ==>"+"\t"+ totalLineCount);
}
}
Now the idea in my mind id for this logic
1) construct the file name you want to use
2) open the file for write
3) each time you call a System.out.println(), make a similar call to write the same message to the file
4) when you are all done, make sure you close the file handle.
I have an rough idea something like this
try{
java.util.Date date= new java.util.Date();
System.out.println(new Timestamp(date.getTime()));
BufferedWriter out = new BufferedWriter(new FileWriter("C://Desktop//output"+new Timestamp(date.getTime())+".txt"));
out.write("some information");
out.close;
}catch(IOException e){
e.printStackTrace();
}
please advise how to that and the name of the file that is generated its name is to be based on timestamp lets assume that name of the output file would be 'output06282012' and that text file should contain the same information that is shown on the console
As far as I can tell, this is the only thing you are actually asking:
Please advise how to that and the name of the file that is generated its name is to be based on timestamp. Lets assume that name of the output file would be 'output06282012' ...
The simple answer is:
String fileName = "output" + new Date().getTime();
You then go on to say:
.... and that text file should contain the same information that is shown on the console
You've got two choices:
You can change where System.out goes to by calling System.setOut(...). (Check the javadoc for details.)
You can create a PrintWriter or PrintStream wrapper for your file stream and write to that instead of writing to System.out.
In my opinion, it is a bad idea to use System.setOut(...) unless you've got no choice. It is a "global action" that affects the entire application. It is better to pass the writer that you want to use as a parameter ...
could you please sow in code as I have done that will clear the understanding
Sorry, I don't write people's programs for them (unless it is an interesting problem!). You need to write and debug the code yourself, using the information provided in the relevant javadocs. You can find the Java documentation online on the Oracle website: http://docs.oracle.com/javase/7/docs/

Categories