Im running this method but for some reason I am not able to find the data record, it keeps going to the catch. Can somebody let me know where I am messing up please. I have the data.txt file in the same directory as the java file.
public static Games[] gamesRecord(){
Games[] game = new Games[50];
try{
Scanner dataFile = new Scanner(new File("data.txt"));
for(int i = 0; i > 50; i++){
game[i].title = dataFile.next();
game[i].releaseDate = dataFile.nextInt();
game[i].redistributions = dataFile.nextInt();
game[i].platformRelease = dataFile.next();
}
}catch(FileNotFoundException e){
System.out.println("File data.txt was not found");
System.out.println("or could not be opened.");
System.exit(0);
}
return game;
}
solve issue by placing full path of the file
Related
im a newbye and this is my first post. Ive made a game aplication on eclipse that works perfectly. It uses a few .txt files for scores and player options.
The problem is when i try to export it as runnable jar file, well that's the problem, it makes a jar file and makes it impossible for me to write on any of the .txt files i have. I know this because ive tried, well not hundreds but getting close, of solutions and some of which allowed me to read the files but still i cant write on them. I realize this is the normal functioning of a jar file, so my questions are:
How can i have/make an external folder to the jar file in the same directory containing all my txt files? So that it can read and write in those files, and, what methods should i use in my existing code?
Im only showing how i read/write one of those files, but its the same for every other file and im also showing some of the comment on other past solutions:
private final String cubesScore = "resF\\score.txt";
//private final String cubesScore = "/score.txt";
//private final String cubesScore = "//resF//score.txt";
try{
/*
try{
File file = new File(cubesScore);
//FileReader reader = new FileReader(new File(new File("."), "score.txt"));
if(file.createNewFile()){
System.out.println("File created successfully!");
} else{
System.out.println("File already exists.");
}
} catch(IOException e){
System.out.println("An error occurred on score.txt!!");
}
*/
Scanner scanner = new Scanner(new File(cubesScore));
//InputStream source = this.getClass().getResourceAsStream(cubesScore);
//Scanner scanner = new Scanner(source);
/*
InputStream inputStream = this.getClass().getResourceAsStream(cubesScore);
InputStreamReader inputReader = new InputStreamReader(inputStream);
BufferedReader reader = new BufferedReader(inputReader);
*/
int value;
int i = 0;
while(scanner.hasNext()){
value = scanner.nextInt();
if(value >= 0){
mostCubesDestroyed[i] = value;
System.out.println(value);
}
else
System.out.println("File corrupted");
++i;
}
scanner.close();
} catch (NullPointerException | FileNotFoundException e) {
System.out.println("File Not Found/Null");
}
write:
try {
PrintWriter out = new PrintWriter(cubesScore);
//OutputStream out = this.getClass().getResourceAsStream(cubesScore);
//out = new PrintWriter(out);
//BufferedWriter out = new BufferedWriter(new FileWriter(cubesScore));
//out.write(mostCubesDestroyed[0]);
//out.newLine();
out.println(mostCubesDestroyed[0]);
System.out.println(mostCubesDestroyed[0]+" Cubes GameMode 0");
//out.write(mostCubesDestroyed[1]);
//out.newLine();
out.println(mostCubesDestroyed[1]);
System.out.println(mostCubesDestroyed[1]+" Cubes GameMode 1");
//out.write(mostCubesDestroyed[2]);
//out.newLine();
out.println(mostCubesDestroyed[2]);
System.out.println(mostCubesDestroyed[2]+" Cubes GameMode 2");
//out.write(mostCubesDestroyed[3]);
//out.newLine();
out.println(mostCubesDestroyed[3]);
System.out.println(mostCubesDestroyed[3]+" Total Cubes Destroyed");
out.close();
} catch (IOException e) {
System.out.println("Error, try again!!");
}
i realize keeping the commented code makes it slightly harder to read but still i wanted to show you some things ive tried...
ive also tried to create the file the first time the app runs but to no success:
try{
File file = new File(cubesScore);
//FileReader reader = new FileReader(new File(new File("."), "score.txt"));
if(file.createNewFile()){
System.out.println("File created successfully!");
} else{
System.out.println("File already exists.");
}
} catch(IOException e){
System.out.println("An error occurred on score.txt!!");
}
so thats my problem, if anyone been here before and somehow managed to find a solution or you simply know how to produce the desired result, which is to read/write on a .txt file external to the jar(because internal leads to all sorts of issues) then pls tell me what i should do, ive seen more then a hundred post and videos and still couldnt find the desired solution.
Edit: This has been resolved below, turns out i needed a . on "/score.txt" well a . in all files.
Did you try this?:
private final String CUBES_SCORE = "./score.txt";
if you want it in a subdirectory, you have to create the subdirectory also.
Also, take a look at this: How do I create a file and write to it in Java?
I think there is some problem in your path
private final String cubesScore = "..\resF\score.txt";
hope it helps :)
I have a text file in the same package as the class I'm accessing it through, so I don't understand why I'm getting this exception. Where did I go wrong here?
public static boolean someMethod(){
File f = new File("input.txt");
try{
Scanner s = new Scanner(file);
s.useDelimiter(""); //I want to parse by one character at a time
while(s.hasNext()){
...
}
}catch (FileNotFoundException e){
...
}
return false;
}
new File("input.txt") is relative to your current working dir. If you want to access packaged files, you can use getResourceAsStream(String).
I am reading files from a GRD file:
File stockInputFile = new File("C://MAX.GRD");
I want to write them to a text file:
File StockOutputFile = new File("C://StockOut.txt");
Am getting some Korean letters. Can you please help me in coding?
Actually I want to store them as float numbers into a text file .. I am able to do the same with C.
fin = fopen("D:\\DailyT\\MeanT\\MEAN.GRD","rb"); // Input file
fout = fopen("D:\\DailyT\\MEAN.TXT","w"); // Output file
fread(&t,sizeof(t),1,fin) ;
for(i=0 ; i < 32 ; i++)
{
fprintf(fout,"\n") ;
for(j=0 ; j < 35 ; j++)
fprintf(fout,"%6.2f",t[i][j]);
}
In Java, writing to a file goes like this:
import java.io.*;
class FileWrite
{
public static void main(String args[])
{
try{
// Create file
FileWriter fstream = new FileWriter("out.txt");
BufferedWriter out = new BufferedWriter(fstream);
out.write("Hello Java");
//Close the output stream
out.close();
} catch (Exception e) {
System.err.println("Error: " + e.getMessage());
}
}
}
See Google to get more tutorials about "java write to file" and "java read from file". Also please update your question once you have actually tried something and met with some difficulty.
I have to read a text and I created a method
public void load(String fname){
try{
BufferedReader reader = new BufferedReader(new FileReader(fname));
String id_cliente = reader.readLine();
while(id_cliente!=null){
String name_surname = reader.readLine();
int num_titoli = Integer.parseInt(reader.readLine());
String[] sb = name_surname.split(" ");
Cliente cl = new Cliente(id_cliente,sb[0],sb[1]);
clientilist.put(Integer.parseInt(id_cliente.substring(1)),cl);
for(int i = 0; i < num_titoli; i++){
cl.addTitolo(String titolo = reader.readLine());
}
id_cliente = reader.readLine();
}
}
catch(FileNotFoundException fnfe){
try{
}
catch(FileNotFoundExeption fnfe){
System.exit(0);
}
}
catch(IOException ioe){
}
}
what I would do is to check if the fname file exists.if it's not a FileNotFoundExceptionwill be thrown.Inside it I have to try to open another file.if it is not present so exit with an error message.how can i do?
In the catch block of the first try catch statement you could put any code you want and it will be executed when the exception occurs. You could read another file, try reading the same file again, ask user to point to the correct file, ...
But as mentioned a better solution is to check if the file exists before you create the reader. And if that fails you can fallback on another file (what if that one fails also?)
In the next code I adapted your method to have a check and throw an exception if file isn't valid. On using that method you can react on that. Note that you haven't opened any readers if you gave 2 invalid filenames.
try{
load(fname);
}catch(Exception e){
try{
load(alternativeFName);
}catch(Exception e){
System.out.println("None of the files are available");
e.printStackTrace();
}
}
And this is how your load function would look like:
public void load(String fname) throws Exception {
// try opening file
File file = new File(fname);
// check if valid file
if( !file.exists() ){
// if no valid file throw exception so we can react on that
throw new Exception("File not available: "+fname);
}
//your code for reading here, at this point you know the file exists
//...
}
It´d be simpler to check first if the file exist, instead of waiting for the exception:
File f = new File(fname);
if (!f.exists()) {
// similarly, check for the existence of the other file, exit if necessary
}
i have a program which select recent files from a directory and compress them into one file.
but i want to stop the program if there is no files in the directory and display an error message like "There is no files in the deirectory"
I tried append this:
if(file.exists)
{ }
else
{ }
but i don't know how to insert it inside my code.
Thank you
{
String source = "C:/Source";
String target = "C:/Target";
File sourceDir = new File(source);
File[] files = sourceDir.listFiles();
if(files.exists())
Arrays.sort(files, new Comparator<File>()
{
public int compare(File f1, File f2)
{
return (int) (f2.lastModified() - f1.lastModified());
}
});
// create the target directory
File targetDir = new File(target);
targetDir.mkdirs();
{
for(int i=0, length=Math.min(files.length, 12); i<length; i++)
files[i].renameTo(new File(targetDir, files[i].getName()));
PrintWriter pw = new PrintWriter(new FileOutputStream("C:/Joined/joined.txt"));
File file = new File("C:/Target");
File[] files2 = file.listFiles();
for (int i = 0; i < files2.length; i++)
{
File currentFile = files2[i];
System.out.println("Processing " + currentFile.getPath() + "... ");
BufferedReader br = new BufferedReader(new FileReader(currentFile));
String line = br.readLine();
while (line != null)
{
pw.println(line);
line = br.readLine();
}
br.close();
}
pw.close();
Thread.sleep(2000);
try
{
ProcessBuilder pb = new ProcessBuilder("c:\\Joined\\Join.bat");
Process p = pb.start();
}
catch (IOException e)
{
e.printStackTrace();
}
}}}
Instead of using System.exit() method it is better to use guard clauses to prevent further execution. Using System.exit() is not a good practice as it halts the flow abruptly. Ideal solution would be
if (file.exists())
return; //Use appropriate returns according to the method signature.
// Block of code that does something with the file.
You can try to call method exit like this:
System.exit(0);
Hope that helps.
If sourceDir does not refer to a directory, you'll get null from listFiles, so that's a first thing you could check.
If it indeed refers to a directory, and the directory is empty, you'll simply get an empty array back from listFiles. So you could use
if (files.length() == 0) {
System.err.println("There is no files in the deirectory");
System.exit(-1);
}
After
File[] files2 = file.listFiles();
you can do
if(files2.length == 0)
{
System.err.println("Error - no files found!");
and if you want the program to completely close,
System.exit(1); //0 denotes normal close, 1 denotes an error
}
and if you want the program to continue to the next step,
break; //exit the current loop
}
After the if(files.exists()), make sure to include brackets ({ and }) with all that chunk of code you just mentioned
For example:
if(files.exists()) {
// code you want it to run if files exist
} else System.err.println("No Files Exist In This Directory...")