Retrieving and Replacing number in text file - java

I need to retrieve and change a number in a text file that will be in the first line. It will change lengths such as "4", "120", "78" to represent the data entries held in the text file.

If you need to change the length of the first line then you are going to have to read the entire file and write it again. I'd recommend writing to a new file first and then renaming the file once you are sure it is written correctly to avoid data loss if the program crashes halfway through the operation.

This will read from MyTextFile.txt and grab the first number change it and then write that new number and the rest of the file into a temporary file. Then it will delete the original file and rename the temporary file to the original file's name (aka MyTextFile.txt in this example). I wasn't sure exactly what that number should change to so I arbitrarily made it 42. If you explain what data entries the file contains I could help you more. Hopefully this will help you some anyways.
import java.util.Scanner;
import java.io.*;
public class ModifyFile {
public static void main(String args[]) throws Exception {
File input = new File("MyTextFile.txt");
File temp = new File("temp.txt");
Scanner sc = new Scanner(input); //Reads from input
PrintWriter pw = new PrintWriter(temp); //Writes to temp file
//Grab and change the int
int i = sc.nextInt();
i = 42;
//Print the int and the rest of the orginal file into the temp
pw.print(i);
while(sc.hasNextLine())
pw.println(sc.nextLine());
sc.close();
pw.close();
//Delete orginal file and rename the temp to the orginal file name
input.delete();
temp.renameTo(input);
}
}

Related

Have java find/read a file from user input?

The program must print the text in file I ask it to read.
The problem is I coded it to read the text from a specific file
File file = new File("numbersonnumbers.txt");
Scanner inputFile = new Scanner(file);
How do I get the program to read the text from a file specified by user input?
*The file is going to be in the same directory/folder as the program so that's not an issue.
EDIT: My prior attempt at user input
Scanner keyboard = new Scanner(System.in);
String filename = keyboard.nextLine();
File file = new File(filename);
Scanner inputFile = new Scanner(file);
Declare a String variable, such as someUserFile, take user input. Then...
File file = new File(someUserFile);
Scanner inputFile = new Scanner(file);
You may want to check their input and append ".txt" to the end of their input.
If this works:
File file = new File("numbersonnumbers.txt");
Scanner inputFile = new Scanner(file);
Then this:
Scanner keyboard = new Scanner(System.in);
String filename = keyboard.nextLine();
File file = new File(filename);
Scanner inputFile = new Scanner(file);
Will do the exact same thing assuming you type numbersonnumbers.txt and type that exactly.
Assuming you type numbersonnumbers.txt exactly, the second snippet does the EXACT same thing as the first snippet.
Firstly you should ask the user the input the filename. Then just replace the "numbersonnumbers.txt" in your code to the variable that you set for the user input.
Scanner in = new Scanner(System.in);
System.out.println("What is the filename?");
String input = in.nextLine();
File file = new File(input);
Scanner input = new Scanner(System.in);
String fileName = input.nextLine();
File file = new File(fileName);
Scanner inputFile = new Scanner(file);
1) The program must print the text in file:
Lets call this file, dataFile.text, or dataFile.dat (either way works)
Assuming that the client will be inputing any file, we must get the file's name...
These Java statements will do the trick:
// Create a Scanner to read user's file name
Scanner userInput = new Scanner(System.in);
// Request the file name from client
System.out.println("Enter name of input file: ");
// Gets client's file name
String fileName = scanFile.nextLine();
// scanFile, scans the new File fileName (client's file), which is located in the src directory. The "src/" represents the path to the file (client's file).
Scanner scanFile = new Scanner(new File("src/" + fileName));
Since the problem states the file, "will be located in the same directory as the program," its not an issue.
---------------------------------------------------------------------------------
2) The problem is I coded it to read the text from a specific file
Yes, all you did was create file of your own called, "numbersonnumbers.txt," this is exactly the code you should be following in the solution to this problem, but instead of typing "numbersonnumbers.text", you will be using the client's input file, which is the String variable "fileName" in the previous code...*
File file = new File("numbersonnumbers.txt");
Scanner inputFile = new Scanner(file);
Corrected: File file = new File("src/" + fileName);
Scanner inputFile = new Scanner(file); // Will scan all the file's data
Corrected More: Scanner inputFile = new Scanner(new File("src/" + fileName));
---------------------------------------------------------------------------------
3) The program must print the text in file
Now to print the data items in the file to the console you simply, copy every item in the file, to an array, list, or tree depending on specifications of implementation, but this is obviously begininer programming so, never mind lists and trees, use an array.
So you have completed upto either Scanner scanFile in #1 or Scanner inputFile in #2
Now, create an array, obviously the type of array would be based on the type of data items in the file... Strings for (e.g., month names) or int for (e.g., ID numbers .. ect)
Assuming the data items in the file are names of months (jan, feb, march) we will make an array of type String.
String[] fileData = new String[100]; // has random length (100)
// Now we will be copying every item from the file into the array, you will need place holder value to keep track of the position during the traversal (stopping at every item) of the file's items.
int i = 0; // itialize the start of the traversal (index 0 of the file items)
while (scanFile.hasNextLine()) { // While file has input on next line, read from file.
fileData[++i] = scanFile.nextLine(); // Input file data and increment i
System.out.println(fileData[i]); // Prints all of the file's data items
} // end while
Respectfully,
-!di0m
You got almost everything you need in your code already. You just need to re-arrange your lines of code properly, and add couple more.
you need two steps: scan what the user enters as full file path, then scan the actual file data as follows:
// Scanner Object to be used for the user file path input
Scanner keyboard = new Scanner(System.in);
// Asks the user to enter the full path of their file
System.out.print("Enter your full file path: ");
// Stores the user input file path as a string
String filename = keyboard.nextLine();
// Creates a File object for the file path, and scans it
Scanner inputFile = new Scanner(new File(filename);
Now you can read the scanned File inputFile. For example you can use a while loop to read one line at a time to read all data and print it out as follows:
// Reads one line at a time, and prints it out
while(inputFile.hasNext) {
System.out.println(inputFile.nextLine());
Or you can put each line's raw data (trimmed and split) in an array and print out each line as an array as follows:
// Declares a String array[] to be used for each line
String[] rawData;
// Reads one line at a time, trims and split the raw data,
// and fills up the array with raw data elements, then prints
// out the array. it repeats the same thing for each line.
while (scanner2.hasNext()) {
rawData = scanner2.nextLine().trim().split("\\s+");
System.out.println(Arrays.toString(rawData));
}

How to insert text after a particular line of a file

I have a file of 250 line. I wanted to insert some text after line 128.
I only found that I can append a text at the end of file
like
try {
PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("outfilename", true)));
out.println("the text");
out.close();
} catch (IOException e) {
//oh noes!
}
That is found on this post How to append text to an existing file in Java
But with no mention to the line number or sth.
There's no way to insert text in the middle of a file because of how file systems work. They implement operations to modify the data blocks of a file and to add and remove blocks from the end of a file. What they don't implement is adding or removing data blocks anywhere else because of inherent complexities of these operations.
What you have to do is copy the first 125 lines to a new file, add what you want to add, and then copy the rest of the file. If you want to you can then rename the new file as the old file so you don't accumulate temporary files.
You can read the original file and write the content in a temp file with new line inserted. Then, delete the original file and rename the temp file to the original file name.
The following code can help you to insert a given string at a given position in an existing file:
public static void writeStrToFileAtGivenLineNum(String str, File file, int lineNum) throws IOException {
List<String> lines = java.nio.file.Files.readAllLines(file.toPath());
lines.add(lineNum, str);
java.nio.file.Files.write(file.toPath(), lines);
}

File contents are wiped when trying to read from Scanner

So I'm trying to read a file using the Scanner, however, all the contents of the file are wiped, and then it reads nothing. Here are the methods I've ran in succession, in my Main method:
private static Scanner x;
private static Formatter y;
public void openMainFile(String name){
try{
x = new Scanner(new File("main.mcmm");
y = new Formatter("main.mcmm");
}catch(Exception e){
GUI.error(2);
}
}
This method runs perfectly fine
public void readModMainFile(){
while(x.hasNext()){
Main.name = x.next();
Main.ver = x.nextFloat();
Main.base = x.nextBoolean();
Main.dev = x.next();
Main.date = x.next();
}
}
After this method runs, the file is empty, and the 'Main.-' variables don't have any values.
Don't open the same file for reading and writing at the same time. Write into a temporary file first, then rename it. Alternatively, you can read the whole file first, store everything, close the Scanner and then you can overwrite the file.
Your Formatter is truncating the output file every time. From your comments in this post, you indicate that the number of variables will remain constant. You could use a temporary file to achieve this (+1 to #biziclop):
File inputFile = new File("main.mcmm");
Scanner scanner = new Scanner(inputFile);
File tempFile = File.createTempFile("main.mcmm",".temp");
Formatter y = new Formatter(tempFile);
y.format("%s", name);
// more reading & formatting, etc.
y.close();
scanner.close();
inputFile.delete();
tempFile.renameTo(inputFile);
Remember to close both the Scanner and Formatter so that the input & output files can be deleted & renamed respectively.

Output the strings inside of multiple .txt files in a directory

I have a folder which file name is: "List of names". Inside that folder i have a 5 ".txt" file documents and each document file names is a person's name.
I want to retrieve the five documents and display the strings inside each documents. How do i do this? I tried this:
import java.io.*;
import java.util.*;
public class Liarliar {
public static void main(String args[])throws IOException{
File Galileo = new File("C:\\List of names\\Galileo.txt");
File Leonardo = new File("C:\\List of names\\Leonardo.txt");
File Rafael = new File("C:\\List of names\\Rafael.txt");
File Donatello = new File("C:\\List of names\\Donatello.txt");
File Michael = new File("C:\\List of names\\Michael.txt");
FileInputStream fis = null;
BufferedInputStream bis = null;
DataInputStream dis = null;
try{
System.out.println("Enter a number list of names:");
Scanner scanner = new Scanner(System.in);
int input = scanner.nextInt();
}catch(FileNotFoundException e){
}catch(IOException e){
}
}
}
Thanks in advance for someones time...
It would be more generic to not hard code the names of the individual files like Galileo.txt. You can create a File representing the directory, and then call listFiles to get all the files in the directory, like
File nameFile = new File(""C:\\List of names");
File[] personFiles = nameFile.listFiles();
Then you can iterate over this File array, and open each file in turn, and read the contents, like
for (File person : personFiles) {
showFileDetails(person);
}
where showFileDetails is a separate method you write for opening the file and displaying the information.
the following lines are not needed as they are meant to take input from user.
System.out.println("Enter a number list of names:");
Scanner scanner = new Scanner(System.in);
int input = scanner.nextInt();
Instead you need to read the files one by one using a FileInputStream or FileReader. See here for an example on how to read data from files. Do this for each of your files.

My java code is flawed, but i dont understand why

I am very new at java and my be missing something very basic. When i run my code i am trying to add value to accounts created in the code. When i try to run the code i recieve an error that a file cannot be found, but i thought that the file was created inside the code.
import java.util.Scanner;
import java.io.File;
import java.io.IOException;
class DoPayroll
{
public static void main(String args[])
throws
IOException
{
Scanner diskScanner =
new Scanner(new File("EmployeeInfo.txt"));
for (int empNum = 1; empNum <= 3; empNum++)
{
payOneEmployee(diskScanner);
}
}
static void payOneEmployee(Scanner aScanner)
{
Employee anEmployee = new Employee();
anEmployee.setName(aScanner.nextLine());
anEmployee.setJobTitle(aScanner.nextLine());
anEmployee.cutCheck(aScanner.nextDouble());
aScanner.nextLine();
}
}
once run i recieve the following error
Exception in thread "main" java.io.FileNotFoundException: EmployeeInfo.txt (No such file or directory)
at java.io.FileInputStream.open(Native Method)
at java.io.FileInputStream.<init>(FileInputStream.java:106)
at java.util.Scanner.<init>(Scanner.java:636)
at DoPayroll.main(jobexe.java:11)
i thought that in the above code using new Scanner(new File("EmployeeInfo.txt") would create the new file once i input a value. Please give me a simple solution and an explanation.
It will create a new file when you write to it. However to read from it, it must already exist. You might like to check it exists with
File file = new File("EmployeeInfo.txt");
if (file.exists()) {
Scanner diskScanner = new Scanner(file);
for (int empNum = 1; empNum <= 3; empNum++)
payOneEmployee(diskScanner);
}
The File object can't find the filename you've passed. You either need to pass the full path of EmployeeInfo.txt to new File(...) or make sure current working directory is the directory that contains this file.
The File constructor does not create a file. Rather, it creates the information in Java needed to access a file on disk. You'd have to actually do file IO in Java using the created File for a new file to be created.
The Scanner constructor requires an existing File. So you need a full path to the real, valid location of EmployeeInfo.txt or to create that file using File I/O first. This tutorial on I/O in Java will help.
You are mistaking instantiating an instance of class File with actually writing a temp file to Disk. Take this line
Scanner diskScanner =
new Scanner(new File("EmployeeInfo.txt"));
And replace it with this
File newFile = File.createTempFile("EmployeeInfo", ".txt");
Scanner diskScanner = new Scanner(newFile);
Edit: Peter makes a good point. I'm face palming right now.
You thought wrong :D A Scanner needs a existing file, which seems quite logical as it reads values and without a existing file its difficult to read. The documentation also states that:
Throws:
FileNotFoundException - if source is not found
So, in short: You must provide a readable, existing file to a scanner.
As the other answer explain, the file is not created just by using new File("EmployeeInfo.txt").
You can check is the file exists using
File file = new File("EmployeeInfo.txt");
if(file.exists()) {
//it exists
}
or you can create the file (if it doesn't exists yet) using
file.createNewFile();
that method returns true if the file was created and false if it already existed.

Categories