File contents are wiped when trying to read from Scanner - java

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.

Related

Why is my scanner not reading from my file?

I'm trying to get my program to read data from a text file and store it in an array. The text file contains data about a planet.
Here is an example:
Mercury
4.151002e10
2.642029e10
-1.714167e9
-3.518882e4
4.355473e4
6.785804e3
3.302e23
My file is named test.txt. It lives in the same directory as my class.java file. I've used System.out.println(new File("test.txt").getAbsolutePath()); to check if the directory path is correct, which it was, and I used System.out.println(new File(".")); to check if it was in the same directory that the code was trying to compile in, which again it was (outputted just a dot which I was led to believe meant it was in the correct directory). I've tried different ways of finding the file, such as renaming it to something else to check it wasn't a keyword, changing the encoding of the file to Unicode, or UTF-8, or ANSI, none of which worked, using .\test in the file to look in the same directory, none of which worked.
Here is my code:
public static void defaultPlanetArray(){
Planet[] solarSystem;
solarSystem = new Planet[9];
PhysicsVector dummyAcceleration = new PhysicsVector();
System.out.println(new File("test.txt").getAbsolutePath());
System.out.println(new File("."));
try{
File file = new File("C:\\Users\\Lizi\\Documents\\Uni Work\\Year 2\\PHYS281\\Project\\test.txt");
Scanner scnr = new Scanner(file);
}
catch(FileNotFoundException e){
System.out.println("File not found!");
}
int i = 0;
while(i<9 && scnr.hasNextLine()){
//read values from file and set as Planet object, then set to array.
i++
}
PhysicsVector and Planet are both classes I have created. PhysicsVector and the rest of Planet apart from this excerpt compile with no problems. When I try to compile this specific bit of code, I get:
.\Planet.java:65: error: cannot find symbol
while(i<9 && scnr.hasNextLine()){
^
I'm guessing this means that the variable scnr is not being created in the try section because it cannot find the file. I think this because when I don't include the try and catch blocks, I get:
.\Planet.java:59: error: unreported exception FileNotFoundException; must be caught or declared to be thrown
Scanner scnr = new Scanner(file);
^
I've also tried the catches FileNotFoundException when I'm first creating the method but that gives me the same error as immediately above.
I could just set the values in the program, but that would give a lot of unnecessary code and be rather inefficient I think.
So my question is, how do I get the scanner to read my values from the file?
As #Lalit Verma pointed the scnr variable you defined lives inside the try - catch block.
Change the code to:
try{
File file = new File("C:\\Users\\Lizi\\Documents\\Uni Work\\Year 2\\PHYS281\\Project\\test.txt");
Scanner scnr = new Scanner(file);
int i = 0;
while(i<9 && scnr.hasNextLine()){
//read values from file and set as Planet object, then set to array.
i++
}
}catch(FileNotFoundException e){
System.out.println("File not found!");
}

How to read a file, included in the package, in Netbeans

I am having difficulty reading a file that I included in a package I am working on for school. The files I need to read, "InputFile1.txt" and InputFile2.txt" are located in a folder called "Lab Exercise 3 Input" in the "Source Packages" folder.
Here is my code for this part:
// create necessary variables
private static ArrayList<String> inputArrayOne = new ArrayList();
private static ArrayList<String> inputArrayTwo = new ArrayList();
private static String nextLine;
private static int currentIndex = 0;
private static int n;
private static int swapCount = 0;
private static String string1;
private static String string2;
/**
* Main method to run
* #param args the command line arguments
*/
public static void main(String[] args) throws FileNotFoundException {
// assign the files to be read
File inputOne = new File("Lab Exercise 3 Input/InputFile1.txt");
File inputTwo = new File("Lab Exercise 3 Input/InputFile2.txt");
// create a scanner objects to read the files
Scanner sc = new Scanner(inputOne);
Scanner sc2 = new Scanner(inputTwo);
// while loop to iterate through the first file
while(sc.hasNextLine()){
// assign the next line of the file to a string
nextLine = sc.nextLine();
// add that string to an array
inputArrayOne.add(nextLine);
} // end while loop
// close the first scanner
sc.close();
What am I doing wrong? I have tried changing the filename to "InputFile1.txt" without any change. This assignment is due tonight 10/27/17 at 11:59 pm, so any help would be greatly appreciated.
I think you miss / .
File inputOne = new File("/Lab Exercise 3 Input/InputFile1.txt");
File inputTwo = new File("/Lab Exercise 3 Input/InputFile2.txt");
You should put your main method in class as well.
public class Example
{
public static void main(String[] args)
{
}
}
Try getting the current directory and adding that to the File location
String dir = System.getProperty("user.dir");
File inputOne = new File(dir + "\\Lab Exercise 3 Input\\InputFile1.txt");
Edit:
I put a file named InputFile1.txt into a folder named Lab Exercise 3 Input into the Source Packages folder
Then put together a quick bit of code and it worked as expected:
String dir = System.getProperty("user.dir");
ArrayList<String> inputArrayOne = new ArrayList<>();
Scanner sc = new Scanner(new File(dir + "\\Lab Exercise 3 Input\\InputFile1.txt"));
while (sc.hasNext()) {
inputArrayOne.add(sc.nextLine());
}
My only other thought is you saved the file as InputFile1.txt but it's also saved as a .txt file, and therefore is actually
InputFile1.txt.txt
Java knows the concept of resource, a "file" on the class path, together with the .class files, and possible packed in a single application .jar. Hence the path uses slashes (/) and is case-sensitive. Also File cannot be used, as te resource might be packed in a jar. And of course a resource is read-only.
InputStream inputOne = getClass().getResourceAsStream(
"/Lab Exercise 3 Input/InputFile1.txt");
InputStream inputTwo = getClass().getResourceAsStream(
"/Lab Exercise 3 Input/InputFile2.txt");
// create a scanner objects to read the files
Scanner sc = new Scanner(inputOne);
Scanner sc2 = new Scanner(inputTwo);
There also is a Scanner constructor with charset, so you could tell that the file is for instance in "UTF-8".

FileReader FileNotFoundException when passing a self-built File

This one's a fun one. I'd appreciate any bit of help, and no previous stackoverflow questions are pointing me in the right location. Docs also weren't very helpful to me.
I'm being thrown a FileNotFoundException with this block of code:
public static int wordOccurance(Word t, File D) throws FileNotFoundException
{
int occurance = 0;
BufferedReader mainReader = new BufferedReader(new FileReader(D));
Scanner kb = new Scanner(mainReader);
My tester file does not cause this to occur: ie. "File tester = new File("C:\read.txt");"
But the problem occurs solely when I pass a File constructed by this method:
public static File makeAndCombineFile(String FileOne, String FileTwo) throws IOException
{
BufferedReader mainReader = null;// null holder value for the later useful bufferedReader
Scanner kb = null;// null holder for later useful Scanner
StringBuilder sb = new StringBuilder();
OTHER CONDITIONS BETWEEN THESE TWO CHUNKS. MOST LIKELY NOT PERTINENT. ALSO RETURN FILE, JUST IF ONE INPUT IS NULL.
else //in case both are good to go and obviously not null
{
mainReader = new BufferedReader(new FileReader(FileOne));
kb = new Scanner(mainReader);
while(kb.hasNext())
sb.append(kb.nextLine() + "\n");
mainReader = new BufferedReader(new FileReader(FileTwo));
kb = new Scanner(mainReader);
while(kb.hasNext())
sb.append(kb.nextLine()+ "\n");
kb.close();
return new File(sb.toString());
}
}
It took me a while to figure out what was going on here, but it looks to me like you think that this line:
return new File(sb.toString());
creates a file on disk containing the text read from the two scanners. It does not. It creates a java.io.File, which is basically a representation of a file path; the path represented by this File is the data read from the scanners. In other words, if FileOne and FileTwo contained the text to War and Peace, then the path represented by that file would be the the text of War and Peace. The file will not have been created on disk; no data will have been written to it. You've just created an object that refers to a file that does not exist.
Use a FileWriter, perhaps in conjunction with a PrintWriter, to save the lines of text into a file; then you can create a File object containing the name of that file and pass it to your other routine:
PrintWriter pw = new PrintWriter(new FileWriter("somename.txt"));
while(kb.hasNext())
pw.println(kb.nextLine());
pw.close();
return new File("somename.txt");

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.

Retrieving and Replacing number in text file

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);
}
}

Categories