I am using the following java code in NetBeans to read and write to a file.
import java.io.*;
import java.util.*;
public class FileReadWrite {
StringTokenizer tokenizer;
BufferedReader inFile;
PrintWriter outFile;
File myFile;
private int[] highscores = new int[3];
public FileReadWrite() throws IOException, FileNotFoundException {
}
public int[] ReadFromSave() throws IOException, FileNotFoundException {
inFile = new BufferedReader(new InputStreamReader(getClass().getResourceAsStream("/files/highscores.txt" )));
tokenizer = new StringTokenizer(inFile.readLine());
int i = 0;
while (tokenizer.hasMoreTokens()) {
highscores[i] = Integer.parseInt(tokenizer.nextToken());
i++;
}
inFile.close();
return highscores;
}
public void SaveFile(int score) throws IOException, FileNotFoundException {
if (score >= highscores[0]){
highscores[2] = highscores[1];
highscores[1] = highscores[0];
highscores[0] = score;
}
else if (score >= highscores[1]){
highscores[2] = highscores[1];
highscores[1] = score;
}
else if (score >= highscores[2]){
highscores[2] = score;
}
PrintWriter outFile = new PrintWriter(new FileWriter("/files/highscores.txt"));
String line = highscores[0] + " " + highscores[1] + " " + highscores[2];
outFile.println(line);
outFile.close();
}
}
I have coded a tetris program and want to save the highscores after each game. And when the user opens up the app next time they are shown the top 3 scores. The ReadFromSave() method started to work fine after I aded "getClass().getResourceAsStream". However I can't get the SaveFile() method working. I gives error "path/file not found". How should I use the PrintWriter in NetBeans so that it saves into the source packages and thus updating the jar. So when the app is fully closed and reopened it has the recent scores printed in. If this is not possible where can I save data so its not lost?
Thank you!!
If you want to be able to save the scores again, using getResourceAsStream isn't really a good idea - that's meant for resources which are bundled with the application, often within a jar file, and often read-only.
You might want to consider using the Java preferences API or work out some specific location for the file to use to store the high scores. Then just write to that file when saving, and read from it while loading. I wouldn't personally use PrintWriter (it swallows exceptions) or FileWriter (you can't specify the character encoding), but both should work. You just need to make sure you load the scores from the same file as you save it to. (It's not clear whether /files/highscores.txt is really an appropriate file to save to... do you have a /files directory? Were you expecting this to be relative to your application's working directory?)
(Also, it's a good idea to start following Java naming conventions, using camelCasing for method names... and use a try-with-resources statement to close writers, streams etc when you're finished with them, instead of manually calling close.)
You are mixing two things here. You are saving to an absolute path '/files/highscores.txt', but you are reading from the classpath, instead of the file system path. You'd have to choose one approach, but I'd stay away from absolute paths here.
However, a better approach might be to use the Preferences API, or Properties.load / store here. And if you're going to do IO operations, it might be better to look into Apache Commons IO, in which reading a file can be as trivial as doing FileUtils.readLines(file, "UTF-8");
Related
I'm trying to read a basic txt file that contains prices in euros. My program is supposed to loop through these prices and then create a new file with the other prices. Now, the problem is that java says it cannot find the first file.
It is in the exact same package like this:
Java already fails at the following code:
FileReader fr = new FileReader("prices_usd.txt");
Whole code :
import java.io.*;
public class DollarToEur {
public static void main(String[] arg) throws IOException, FileNotFoundException {
FileReader fr = new FileReader("prices_usd.txt");
BufferedReader br = new BufferedReader(fr);
FileWriter fw = new FileWriter("prices_eur");
PrintWriter pw = new PrintWriter(fw);
String regel = br.readLine();
while(regel != null) {
String[] values = regel.split(" : ");
String beschrijving = values[0];
String prijsString = values[1];
double prijs = Double.parseDouble(prijsString);
double newPrijs = prijs * 0.913;
pw.println(beschrijving + " : " + newPrijs);
regel = br.readLine();
}
pw.close();
br.close();
}
}
Your file looks to be named "prices_usd" and your code is looking for "prices_usd.txt"
There are a couple of things you need to do:
Put the file directly under the project folder in Eclipse. When your execute your code in Eclipse, the project folder is considered to be the working directory. So you need to put the file there so that Java can find it.
Rename the file correctly with the .txt extn. From your screen print it looks like the file does not have an extension or may be it's just not visible.
Hope this helps!
It is bad practice to put resource files (like prices_usd.txt) in a package. Please put it under the resources/ directory. If you put it directly in the resources/ directory, you can access the file like this:
new FileReader(new File(this.getClass().getClassLoader().getResource("prices_usd.txt").getFile()));
But if you really have a good reason to put it in the package, you can access it like this:
new FileReader("src/main/java/week5/practicum13/prices_usd.txt");
But this will not work when you export your project (for example: as a jar).
EDIT 0: Also of course, your file's name needs to be "prices_usd.txt" and not just "prices_usd".
EDIT 1: The first (recommended) solution does return a string on .getFile() which can not directly be passed to the new File(...) constructor when the application is built / not run in the IDE. Spring has a solution to it though: org.springframework.core.io.ClassPathResource.
Simply use this code with Spring:
new FileReader(new ClassPathResource("prices_usd.txt").getFile());
I want to print the objects within an ArrayList (projects) to a file as a string. They are currently stored as 'Projects' which is defined in a different class.
When I use System.out.print rather than outputStream.print, it works fine, and the information appears as expected. As soon as I want it in a file, the file doesn't appear.
import java.io.PrintWriter;
import java.util.ArrayList;
import java.io.FileOutputStream;
import java.io.FileNotFoundException;
public class FileController
{
public static void finish(ArrayList<Project> projects)
{
PrintWriter outputStream = null;
try
{
outputStream = new PrintWriter(new FileOutputStream("project.txt"));
}
catch (FileNotFoundException e)
{
System.out.println("Error opening the file stuff.txt.");
System.exit(0);
}
System.out.println("Writing to file");
for(int i = 0; i < projects.size(); i++)
{
//System.out.print(projects.get(i) + "," + projects.get(i).teamVotes);
outputStream.println(projects.get(i) + "," + projects.get(i).teamVotes);
}
outputStream.close();
System.out.println("End of Program");
}
}
I'm sure the file is somewhere, your code has no errors. At least, I don't see any. Maybe you need to call outputStream.flush() since the constructor you are using uses automatic line flushing from the given OutputStream, see the documentation. But afaik closing the stream will flush automatically.
Your path "project.txt" is relative, so the file will be placed where your code is being executed. Usually, that is near the .class files, check all folders around there in your project.
You can also try an absolute path like
System.getProperty("user.home") + "/Desktop/projects.txt"
then you will easily find the file.
Anyways, you should use Javas NIO for writing and reading files now. It revolves around the classes Files, Paths and Path. The code may then look like
// Prepare the lines to write
List<String> lines = projects.stream()
.map(p -> p + "," + p.teamVotes)
.collect(Collectors.toList());
// Write it to file
Path path = Paths.get("project.txt");
Files.write(path, lines);
and that's it, easy.
I don't understand how to use TextIO's readFile(String Filename)
Can someone please explain how can I read an external file?
public static void readFile(String fileName) {
if (fileName == null) // Go back to reading standard input
readStandardInput();
else {
BufferedReader newin;
try {
newin = new BufferedReader( new FileReader(fileName) );
}
catch (Exception e) {
throw new IllegalArgumentException("Can't open file \"" + fileName + "\" for input.\n"
+ "(Error :" + e + ")");
}
if (! readingStandardInput) { // close current input stream
try {
in.close();
}
catch (Exception e) {
}
}
emptyBuffer(); // Added November 2007
in = newin;
readingStandardInput = false;
inputErrorCount = 0;
inputFileName = fileName;
}
}
I had to use TextIO for a school assignment and I got stuck on it too. The problem I had was that using the Scanner class I could just pass the name of the file as long as the file was in the same folder as my class.
Scanner fileScanner = new Scanner("data.txt");
That works fine. But with TextIO, this won't work;
TextIO.readfile("data.txt"); // can't find file
You have to include the path to the file like this;
TextIo.readfile("src/package/data.txt");
Not sure if there is a way to get it to work like the Scanner class or not, but this is what I've been doing in my course at school.
The above answer (about using the correct file name) is correct, however, as a clarification, make sure that you actually use the proper file path. The file path suggested above, i.e. src/package/ will not work in all circumstances. While this will be obvious to some, for those of you who need clarification, keep reading.
For example (and I use NetBeans), if you have already moved the file into NetBeans, and the file is already in the folder you want it to be in, then right click on the folder itself, and click 'properties'. Then expand the 'file path' section by clicking on the three dots next to the hidden file path. You will see the actual file path in its entirety.
For example, if the entire file path is:
C:\Users..\NetBeansProjects\IceCream\src\icecream\icecream.dat
Then, in the java code file itself, you can write:
TextIo.readfile("src/icecream/icecream.dat");
In other words, make sure you include the words 'src' but also everything that follows the src as well. If it's in the same folder as the rest of the files, you won't need anything prior to the 'src'.
I am trying to read 2 files after i read the files i want to get their contents and manipulate the contents of the two files then update a new file which is the output. The files are in the same folder as the program but the program always throws a FileNotFoundException.
Below is my code:-
import java.io.*;
import java.util.Scanner;
public class UpdateMaster {
public static void main(String[] args)
{
String master = "Customer.dat";
String trans = "Transactns.dat";
String newMaster = "Temp.txt";
Scanner inputStreamMaster = null;
Scanner inputStreamTrans = null;
PrintWriter inputStreamNewMaster = null;
try
{
inputStreamMaster = new Scanner(new File(master));
inputStreamTrans = new Scanner(new File(trans));
inputStreamNewMaster = new PrintWriter(newMaster);
}
catch(FileNotFoundException e)
{
System.out.println("Error: you opend a file that does not exist.");
System.exit(0);
}
catch(IOException e)
{
System.out.println("Error.");
System.exit(0);
}
do
{
String transLine = inputStreamTrans.nextLine();
String masterLine = inputStreamMaster.nextLine();
String[] transLineArr = transLine.split(",");
String[] masterLineArr = masterLine.split(",");
int trAccNo = Integer.parseInt(transLineArr[0]);
int sales = Integer.parseInt(transLineArr[1]);
int masterAccNo = Integer.parseInt(masterLineArr[0]);
int balance = Integer.parseInt(masterLineArr[1]);
while(masterAccNo== trAccNo){
inputStreamNewMaster.println(trAccNo+ " , "+masterAccNo);
masterLine = inputStreamMaster.nextLine();
masterLineArr = masterLine.split(",");
masterAccNo = Integer.parseInt(masterLineArr[0]);
balance = Integer.parseInt(masterLineArr[1]);
}
balance = balance + sales;
inputStreamNewMaster.println(masterAccNo+ " , "+balance);
}while(inputStreamTrans.hasNextLine());
inputStreamMaster.close();
inputStreamTrans.close();
inputStreamNewMaster.close();
//System.out.println(" the line were written to "+ newMaster);
}
}
Like #Ankit Rustagi said in the comments, you need the full path of the files if you want to keep the current implementation.
However, there is a solution where you only need the file names: use BufferedReader / BufferedWriter. See here an example on how to use these classes (in the example it uses the full path but it works without it too).
Use absolute path
String master = "C:/Data/Customer.dat";
String trans = "C:/Data/Transactns.dat";
String newMaster = "C:/Data/Temp.txt";
The code works for me, i guess you misspelled some filename(s) or your files are in the wrong folder. I created your files on the same level as the src or the project. Also this is the folder where the files are exspected.
There's nothing wrong with using relative paths like tihis. What's happening is that your program is looking for the files in the directory where you execute the program, which doesn't have to be the folder of the program. You can confirm this by logging the absolute path of the files before you try to read them. For example:
File masterFile = new File(master);
System.out.printf("Using master file '%s'%n", masterFile.getAbsolutePath());
inputStreamMaster = new Scanner(masterFile);
In general you should not hardcode file paths but allow the user to specify them in someway, for example using command line arguments, a configuration file with a well known path, or an interactive user interface.
There is a way to locate the program's class file but it's a little tricky because Java allows classes to be loaded from compressed archives that may be located in remote systems. It's better to solve this problem in some other manner.
Try this:
String current = new java.io.File( "." ).getCanonicalPath();
System.out.println("I look for files in:"+current);
To see what directory your program expects to find its input files. If it shows the correct directory, check spelling of filenames. Otherwise, you have a clue as to what's gone wrong.
This is my code to read a text file. When I run this code, the output keeps saying "File not found.", which is the message of FileNotFoundException. I'm not sure what is the problem in this code.
Apparently this is part of the java. For the whole java file, it requires the user to input something and will create a text file using the input as a name.
After that the user should enter the name of the text file created before again (assume the user enters correctly) and then the program should read the text file.
I have done other parts of my program correctly, but the problem is when i enter the name again, it just can not find the text file, eventhough they are in the same folder.
public static ArrayList<DogShop> readFile()
{
try
{ // The name of the file which we will read from
String filename = "a.txt";
// Prepare to read from the file, using a Scanner object
File file = new File(filename);
Scanner in = new Scanner(file);
ArrayList<DogShop> shops = new ArrayList<DogShop>();
// Read each line until end of file is reached
while (in.hasNextLine())
{
// Read an entire line, which contains all the details for 1 account
String line = in.nextLine();
// Make a Scanner object to break up this line into parts
Scanner lineBreaker = new Scanner(line);
// 1st part is the account number
try
{ int shopNumber = lineBreaker.nextInt();
// 2nd part is the full name of the owner of the account
String owner = lineBreaker.next();
// 3rd part is the amount of money, but this includes the dollar sign
String equityWithDollarSign = lineBreaker.next();
int total = lineBreaker.nextInt();
// Get rid of the dollar sign;
// we use the subtring method from the String class (see the Java API),
// which returns a new string with the first 'n' characters chopped off,
// where 'n' is the parameter that you give it
String equityWithoutDollarSign = equityWithDollarSign.substring(1);
// Convert this balance into a double, we need this because the deposit method
// in the Account class needs a double, not a String
double equity = Double.parseDouble(equityWithoutDollarSign);
// Create an Account belonging to the owner we found in the file
DogShop s = new DogShop(owner);
// Put money into the account according to the amount of money we found in the file
s.getMoney(equity);
s.getDogs(total);
// Put the Account into the ArrayList
shops.add(s);
}
catch (InputMismatchException e)
{
System.out.println("File not found1.");
}
catch (NoSuchElementException e)
{
System.out.println("File not found2");
}
}
}
catch (FileNotFoundException e)
{
System.out.println("File not found");
} // Make an ArrayList to store all the accounts we will make
// Return the ArrayList containing all the accounts we made
return shops;
}
If you are working in some IDE like Eclipse or NetBeans, you should have that a.txt file in the root directory of your project. (and not in the folder where your .class files are built or anywhere else)
If not, you should specify the absolute path to that file.
Edit:
You would put the .txt file in the same place with the .class(usually also the .java file because you compile in the same folder) compiled files if you compile it by hand with javac. This is because it uses the relative path and the path tells the JVM the path where the executable file is located.
If you use some IDE, it will generate the compiled files for you using a Makefile or something similar for Windows and will consider it's default file structure, so he knows that the relative path begins from the root folder of the project.
Well.. Apparently the file does not exist or cannot be found. Try using a full path. You're probably reading from the wrong directory when you don't specify the path, unless a.txt is in your current working directory.
I would recommend loading the file as Resource and converting the input stream into string. This would give you the flexibility to load the file anywhere relative to the classpath
If you give a Scanner object a String, it will read it in as data. That is, "a.txt" does not open up a file called "a.txt". It literally reads in the characters 'a', '.', 't' and so forth.
This is according to Core Java Volume I, section 3.7.3.
If I find a solution to reading the actual paths, I will return and update this answer. The solution this text offers is to use
Scanner in = new Scanner(Paths.get("myfile.txt"));
But I can't get this to work because Path isn't recognized as a variable by the compiler. Perhaps I'm missing an import statement.
This should help you..:
import java.io.*;
import static java.lang.System.*;
/**
* Write a description of class InRead here.
*
* #author (your name)
* #version (a version number or a date)
*/
public class InRead
{
public InRead(String Recipe)
{
find(Recipe);
}
public void find(String Name){
String newRecipe= Name+".txt";
try{
FileReader fr= new FileReader(newRecipe);
BufferedReader br= new BufferedReader(fr);
String str;
while ((str=br.readLine()) != null){
out.println(str + "\n");
}
br.close();
}catch (IOException e){
out.println("File Not Found!");
}
}
}
Just another thing... Instead of System.out.println("Error Message Here"), use System.err.println("Error Message Here"). This will allow you to distinguish the differences between errors and normal code functioning by displaying the errors(i.e. everything inside System.err.println()) in red.
NOTE: It also works when used with System.err.print("Error Message Here")