producing some text file using a for loop in java? - java

I am going to produce some text files(number of files is entered by user) using a for loop, but when the program runs only one file is produced because the file name doesn't change. I don't know how to change the names of file every time. my code is below which produces only one text file not as many as the user enters.
Scanner sc = new Scanner(System.in);
int p1 = sc.nextInt();
for (int i = 0; i < p1; i++) {
try {
FileWriter f = new FileWriter("textfile.txt");
f.close();
} catch (IOException e) {
e.printStackTrace();
}
}

try to give like this in for loop to create multiple file
FileWriter f = new FileWriter("textfile_"+i+".txt");

Instead of having a constant name for the file, use a String variable. If you want that the name of the file is unique each time you run your program, you can write something like this:
Scanner sc = new Scanner(System.in); int p1 = sc.nextInt();
for (int i = 0; i < p1; i++) {
try {
String filename = "textfile_" + System.currentTimeMillis() + ".txt"
FileWriter f = new FileWriter(filename);
f.close();
} catch (IOException e) {
e.printStackTrace();
}}
System.currentTimeMillis() returns the number of miliseconds from 1.1.1970 UTC

Related

java:40: error: exception FileNotFoundException is never thrown in body of corresponding try statement

I am trying to open a file with Java. If the operation does not work, my program should output The file was not found, please download file with name DateTemp.csv.. Here is my code:
File myFile = new File("DateTemp.csv"); //File Name
Scanner inputFile = new Scanner(myFile); //scanner to input file name
try {
//Try to display one too many array elements.
myFile = new File("DateTemp.csv");
for (int i = 0; i <= templow.length; i++);
for (int i = 0; i <= temphigh.length; i++);
//System.out.println(temphigh[i]);
//System.out.println(templow[i]);
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Invalid array index exceeds Array Size."); //catch block to declare the array index was too large
} catch (FileNotFoundException e) {
System.out.println("The File was not Found, please download file with name DateTemp.csv");
System.exit(1);
}
Put the Scanner inputFile = new Scanner(myFile); code inside of the try block

Delete method doesn't delete - Java

I made a program that can display and edit a record. The problem is that I cannot delete the file that I wanted to delete to replace it with the edited ones.
public class Laboratory {
public static void main(String[] args) throws FileNotFoundException,InterruptedException,IOException {
// paste your script here ;)
String fileName = "record.txt";
String filepath = "D:\\Programming\\Java\\Program - Script Test\\files\\" + fileName;
String in = "";
File file = new File(filepath);
Scanner fscan = new Scanner(file);
Scanner scan = new Scanner(System.in);
PrintWriter pw = null;
int linecount = 1;
String content = "";
// reads the file according to the given line count.
for(int i = 0; i < linecount; i++) {
content = fscan.nextLine();
}
// creates the template file.
String tempPath = "D:\\Programming\\Java\\Program - Script Test\\files\\" + "temp.txt";
String contentParts[] = content.split("\\|");
System.out.println(content);
System.out.println(contentParts[1]);
System.out.println(contentParts[2]);
System.out.print("change the name >> ");
in = scan.nextLine();
// edits the scanned content from the file.
String finalContent = "|" + in + "|" + contentParts[2];
System.out.println(finalContent);
file = new File(filepath);
fscan = new Scanner(file);
// scans the original record and pastes it in a new template file.
try {
pw = new PrintWriter(new FileOutputStream(tempPath));
if(linecount == 1) {
content = fscan.nextLine();
pw.println(finalContent);
while(fscan.hasNextLine()) {
content = fscan.nextLine();
pw.println(content);
}
}
else if (linecount > 1) {
for (int i = 0; i < linecount - 1; i++) {
content = fscan.nextLine();
pw.println(content);
}
pw.println(finalContent);
content = fscan.nextLine();
while (fscan.hasNextLine()) {
content = fscan.nextLine();
pw.println(content);
}
}
}
catch(FileNotFoundException e) {
System.out.println(e);
}
finally {
pw.close();
fscan.close();
}
// deletes the original record
file.delete();
} // end of method
} // script test class end
Although, I made a test program that successfully deletes a file.
public class delete {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
File file = new File("helloworld.txt");
String in;
System.out.println("Press ENTER to DELETE file.");
in = scan.nextLine();
file.delete();
} // main method end
} // program end
My file path is right and I don't really know what causes the problem. Is there a solution to fix this?
Explanation
file.delete() does not throw an error if it failed. And it failed here, as indicated by its return value being false.
Execute Files.delete(file.toPath()) instead and you will see the exact error reason, which is:
Exception in thread "main" java.nio.file.FileSystemException: D:\Programming\Java\Program - Script Test\files\record.txt: The process cannot access the file because it is being used by another process
at java.base/sun.nio.fs.WindowsException.translateToIOException(WindowsException.java:92)
at java.base/sun.nio.fs.WindowsException.rethrowAsIOException(WindowsException.java:103)
at java.base/sun.nio.fs.WindowsException.rethrowAsIOException(WindowsException.java:108)
at java.base/sun.nio.fs.WindowsFileSystemProvider.implDelete(WindowsFileSystemProvider.java:274)
at java.base/sun.nio.fs.AbstractFileSystemProvider.delete(AbstractFileSystemProvider.java:105)
at java.base/java.nio.file.Files.delete(Files.java:1146)
at Laboratory.main(Laboratory.java:123)
So
The process cannot access the file because it is being used by another process
Because you still have a scanner to the file open, you are blocking yourself from deleting it. Close the scanner and it will work.
Your code opens two (not one) scanner to file, one at the beginning:
Scanner fscan = new Scanner(file);
which you use during your initial loop:
for (int i = 0; i < linecount; i++) {
content = fscan.nextLine();
}
and then later on you create a second one:
fscan = new Scanner(file);
which you also close during your finally block:
fscan.close();
But you did never close the first scanner.
Solution
Add
fscan.close();
After the initial loop:
for(int i = 0; i < linecount; i++) {
content = fscan.nextLine();
}
fscan.close();
and the file.delete() will succeed.
NIO
As explained, file.delete() is a poorly designed method. Prefer Files.delete(path).
In general, if you do not have a good reason to use the old cumbersome file IO library, dont. Use NIO instead (Java 7+).

Running Junit Test on Class that gets input from file , but Scanner and BufferedReader objects lead to stack overflow error in the tests

I am running JUnit tests on a method checkFile(), the method is supposed to check a file for some values and prompt the user when the values in the file are not permissible for a new file. If the file is ok, the method returns a value.
The problem is my test fails due to a StackOverflow error each time and never actually runs. The error points to the scanner object I am using to access the file.
I think the issue may be related to my use of recursion in the method but I cannot think of any other way to do this without writing redundant code if I don't use recursion.
Fyi, I know I could break this method into smaller methods but this assignment requires that I do not create any additional methods. I have tried to use BufferedReader Reader = new BufferedReader ( new FileReader(file))
also but the same issue occurs.
Fyi , line 137 in the Simulator class is where I instantiate the object Scanner Reader = new Scanner(file);
public ArrayList<Customer> checkFile(int stops, File file) {
Simulator sim = new Simulator();
int linesProcessed = 0;
String customerdata = " ";
String[] dataArray;
int[] parsedVals = new int[4];
String delimiter = " ";
List<Customer> custList = new ArrayList<Customer>();
List idArray = new ArrayList();
try {
Scanner Reader =new Scanner(file);//--> this appears to be causing the issue.
while (Reader.hasNextLine()) {
customerdata = Reader.nextLine();
dataArray = customerdata.split(delimiter);
for (int i = 0; i < dataArray.length; i++) {
try {
parsedVals[i] = Integer.parseInt(dataArray[i]);
if (parsedVals[i] <=0 ){
System.out.println("file input 0");
throw new IllegalArgumentException();
}
if (i==2 | i==3 ){
if(parsedVals[i]>stops){
throw new IllegalArgumentException();
}
}
} catch (NumberFormatException ex) {
if (linesProcessed == 0) {
System.out.println("Each line must have four integers. Try again.");
} else {
System.out.println(" Regular:Data in input file is not correct. Try again.");
}
sim.getInputFile();
sim.checkFile(stops, file);
}
catch(IllegalArgumentException args){
System.out.println("Data in input file is not correct. Try again.");
file =sim.getInputFile();
custList = sim.checkFile(stops, file);
}
}
try{
if(parsedVals[2]==parsedVals[3]) {
throw new IllegalArgumentException();
}
custList.add(new Customer(parsedVals[0], parsedVals[1], parsedVals[2], parsedVals[3]));
}catch(IllegalArgumentException ex){
System.out.println("Data in input file is not correct. Try again.");
file =sim.getInputFile();
custList = sim.checkFile(stops, file);
}
idArray.add(linesProcessed, parsedVals[0]);
linesProcessed++;
}
boolean duplicates = false;
for (int j = 0; j < idArray.size(); j++) {
for (int k = j + 1; k < idArray.size(); k++) {
if (k != j && idArray.get(k) == idArray.get(j)) {
duplicates = true;
}
}
}
if (duplicates) {
System.out.println(" Duplicates: Data in input file is not correct. Try again.");
File newfile = sim.getInputFile();
sim.checkFile(stops, newfile);
}
}
catch (FileNotFoundException ex) {
System.out.println("File not found, try again.");
file = sim.getInputFile();
sim.checkFile(stops, file);
}
return custList;
}
There are many tests but all the tests essentially do something similar. See bellow :

Using try/catch for files in java

I'm having issues with using try-catch blocks in java. I'm writing a method that reads a user input file and prints it out to the console. This is what I have -
static Scanner input = new Scanner(System.in);
public static String readingFiles(String fileout) {
boolean find = false;
while(!find) {
try {
File f = new File(input.nextLine());
Scanner scan = new Scanner(f);
} catch (FileNotFoundException e) {
System.out.println("File Not Found.");
}
}
ArrayList<String> list = new ArrayList<String>();
while (input.hasNext())
{
list.add(input.nextLine());
}
String output = list.toString();
return output;
}
It just seems like a mess and I have no idea what to do with it at this point. I had it working a few times, in that it would output what the file said but then if I purposefully entered the wrong file name it would loop "file not found" endlessly and I couldn't figure out how to return the loop to the beginning so the user could input a different file name.
Now it just does nothing even when i enter the correct file name, it returns nothing until i press enter again and it'll return file not found.
I call it using this in my main menu method -
case 1:
System.out.println("You chose Read File. Enter your file name: ");
System.out.println(Question4.readingFiles(input.nextLine()));
pressEnter();
break;
edit: I now have this, which works but only prints the first line of my file?
public static String readingFiles(String fileout) {
boolean find = false;
String result = "";
while (!find) {
try {
File read = new File(fileout);
Scanner check = new Scanner(read);
result = check.nextLine();
find = true;
check.close();
} catch (FileNotFoundException e) {
System.out.println("File Not Found. Please try again.");
break;
}
}
return result;
}
Check the following code.
public static void readFiles() throws Exception {
int i = 1;
BufferedReader reader = null;
Scanner input = null;
boolean fileFound = true;
while(i <= 5){
System.out.print("Enter a file name::::");
input = new Scanner(System.in);
if(input.hasNextLine()){
try {
File f = new File(input.nextLine());
reader = new BufferedReader(new FileReader(f));
String str = null;
while((str = reader.readLine()) != null){
System.out.println(str);
}
} catch (FileNotFoundException e) {
System.out.println("File Not Found");
fileFound = false;
i++;
continue;
} catch (IOException e) {
System.out.println("IOException");
i++;
continue;
} catch (Exception e) {
System.out.println("Some Other Exception");
i++;
continue;
} finally{
if(fileFound)
reader.close();
}
}
i++;
}
}
Please note this method will read files 5 times. If you want to change it, you can pass an int parameter to the method and accordingly change the first while condition. Ensure you give complete path of the file with escape characters. For example, if file location is 'C:\abc.txt', you need to input 'C:\\abc.txt'. Else, it will display 'File Not Found' in console.
public class readingFiles {
public static String readingFiles(String fileout) {
try {
//find a file with the same name as the value of "fileout"
File f = new File(fileout);
Scanner scan = new Scanner(f);
//create a list to hold the file output
ArrayList<String> list = new ArrayList<String>();
//loop through the output line by line and add to the list
while (scan.hasNext())
{
list.add(scan.nextLine());
}
//convert the list into a String value to pass back to the caller
String output = list.toString();
scan.close();
return output;
} catch (FileNotFoundException e) {
//if file is not found, return a value of -1
System.out.println("File Not Found.");
return("-1");
}
}
Okay a few things:
Your first while loop is unnecessary. I think you are trying to loop through files in the folder to look for a specific file name. However the Scanner scan = new Scanner(f); line already does this.
The reason your code infinitely prints "File not found." is because you never set the find condition to true to exit the loop.
You never use the fileout value you pass into the method. And your code asks the user for the filename input twice (once in the main method, once in the readingFiles method).
Using a list, then converting to String results in an output of [line1, line2, line3, etc] not sure if this is what you want.
As for why your second attempt prints only the first line, You have removed the while loop which loops through the file reading every line, therefore it only reads one line before stopping.

Saving Stats with Java IO

I have a file and a basic reader and writer set up but when I change the value it doesn't write the new value
Here's the code:
int constitutionLevel, strengthLevel;
int[] saveStats = { constitutionLevel, strengthLevel };
int constitutionLevelLocation = 0;
int strengthLevelLocation = 1;
public StatSaver()
{
constitutionLevel = Constitution.getConstitutionLevel();
strengthLevel = Strength.getStrengthLevel();
}
public void startSaving()
{
readPlayer("SaveManagement/Stats/save.txt");
updatePlayerStats();
savePlayer("SaveManagement/Stats/save.txt");
}
private void updatePlayerStats()
{
System.out.println("Saving Stats...");
System.out.println(constitutionLevel);
constitutionLevel = saveStats[constitutionLevelLocation];
strengthLevel = saveStats[strengthLevelLocation];
System.out.println(constitutionLevel);
System.out.println("Done Saving Stats");
}
private void readPlayer(String filePath)
{
File inputFile;
BufferedReader inputReader;
try
{
inputFile = new File(filePath);
inputReader = new BufferedReader(new FileReader(inputFile));
for (int i = 0; i < saveStats.length; i++)
{
saveStats[i] = Integer.parseInt(inputReader.readLine());
}
inputReader.close();
} catch (Exception e) { e.printStackTrace(); }
}
private void savePlayer(String filePath)
{
File outputFile;
BufferedWriter outputWriter;
try
{
outputFile = new File(filePath);
outputWriter = new BufferedWriter(new FileWriter(outputFile));
outputWriter.write(saveStats[0] + "\n");
outputWriter.write(saveStats[1] + "\n");
//for (int i = 0; i < saveStats.length; i++)
//{
// outputWriter.write(saveStats[i] + "\n");
//}
outputWriter.close();
} catch (Exception e) { e.printStackTrace(); }
}
As you can see I have a line of code commented out but the two lines of code right above do the same thing I just have to type a few more things, I could change it for something bigger but since I have two stats right now I am not in any rush. The only solution that is short term would be to change the value in the .txt file but that would not work when I public the game because everybody would put the stat at infinity. Anyways please help and Thanks in advance!
So, in your startSaving() method, you read in information from readPlayer() (which I assume is the old values stored in the file), and then place the values into the array. In the updatePlayerStats(), you take the values in the array, and put them into the two variables (overwriting what was placed in them by the constructor). Lastly, the savePlayer() method takes the information from the array, and saves them into the file. At no point did you change the values in the array, so no new numbers are being added to the file.

Categories