Java-Reading and Writing to Files-File not Found - java

So I am working on this game where I have a high score stored in a text file. I am following the newboston's tutorial on how to read and write to file. Right now I am testing whether the read class works and it is not working. It says cannot find file when I put the text exactly like how it is and the file is in my package so I don't have to say a path. Here is the method code in my game using both read and write classes:
private int getHighScore(int change, int newScore) {
if (change==1) {
readFile r=new readFile();
r.openFile();
String fileScore=r.readtext();
r.closeFile();
int score=Integer.parseInt(fileScore);
return score;
}
else {
writeToFile w=new writeToFile();
w.openFile();
w.addRecords(newScore);
w.closeFile();
return newScore;
}
}
Here is the read class:
import java.io.*;
import java.util.*;
public class readFile {
private Scanner read;
public void openFile() {
try {
read=new Scanner(new File("highScore.txt"));
}
catch(Exception e){
System.out.println("Could not find file.");
}
}
public String readtext() {
String score=read.next();
return score;
}
public void closeFile() {
read.close();
}
}
Also here is the write file. I am concerned that this class might not work either as it looks like it maybe creating a new file and writing to that new one when I just want to write to an existing file I already have called "highScore.txt" Anyways here is the write class:
import java.util.*;
public class writeToFile {
private Formatter x;
public void openFile() {
try {
x=new Formatter("highScore.txt");
}
catch(Exception e) {
System.out.println("Can not open that file.");
}
}
public void addRecords(int newScore) {
String score=""+newScore;
x.format("%s", score);
}
public void closeFile() {
x.close();
}
}
So I am wondering why it is not working and thanks in advance.

If your file exists in the same location where ReadFile and WriteFile exists. Then you can use the below code.
URL url = getClass().getResource("highScore.txt");
Scanner read=new Scanner(new File(url.getPath()));

Ok I solved it. The problem was wrong location and I still did not have to give a path. So basically I looked at this thread: The system cannot find the file specified in java
The part of the thread is listing the files in the directory. When I did that, I noticed everything it mentioned was in the project folder. I moved my file from the src folder to the project folder and it worked. So if you come across a problem where you know you spelled the file name right but get file does not exist, make sure that your file is in the project folder and NOT in the src folder.

Related

.getAbsolutePath() function works differently in eclipse and cmd

I have a program that scans a file.
import java.util.*;
import java.io.*;
public class testProgram {
private static Scanner scan;
private static File file;
private static String filePath;
private static String content;
public static void main(String[] args) throws InterruptedException{
filePath = "files\\text.txt";
file = new File(filePath);
file.getAbsoluteFile();
try {
scan = new Scanner(file);
while(scan.hasNextLine()) {
content = scan.nextLine();
System.out.println(content);
}
Thread.sleep(10000);
}
catch (FileNotFoundException e) {
System.out.println("file not found");
Thread.sleep(10000);
}
}
}
I tried to run this in eclipse and it works fine. The absolute path shows like this:
"D:\Programming\Java\Test Program\files\text.txt"
When I compiled it into batch file and run the program in cmd, the program doesn't work because the absolute path is now different:
"D:\Programming\Java\Test Program\src\files\text.txt"
This is what my batch file looks like:
echo off
cls
java testProgram
Although the java file (the one that works in Eclipse) and the batch file (that doesn't work) were in the same folder but the batch file acts differently in terms of file paths. I want them to work in eclipse or in cmd. Why does this happen and is it possible to resolve this? Sorry for the trouble, Beginner here :)

How to pass a file name as parameter, create and then read the file

I have a method as follows:
public(String input_filename, String output_filename)
{
//some content
}
how to create an input_filename at run time and read the input_filename .I have to pass input_filename as a parameter
Please be patient as I am new to Java
Here a complete sample:
Save it as Sample.java
compile it with: javac Sample.java
run it with: java Sample "in.txt" "out.txt"
or: java Sample
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
public class Sample {
public static void main(String[] args) throws IOException {
if(args.length == 2)
{
doFileStuff(args[0],args[1]);
}
else {
doFileStuff("in.txt","out.txt");
}
}
public static void doFileStuff(String input_filename, String output_filename) throws IOException {
if(!Files.exists(Paths.get(input_filename)))
{
System.err.println("file not exist: " + input_filename);
return;
}
if(!Files.exists(Paths.get(output_filename)))
{
System.err.println("file still exist, do not overwrite it: " + output_filename);
return;
}
String content = new String(Files.readAllBytes(Paths.get(input_filename)));
content += "\nHas added something";
Files.write(Paths.get(output_filename), content.getBytes(StandardCharsets.UTF_8));
}
}
I'm unsure what you want to do with this method, but I hope this can help you a bit.
If you want inputs during runtime, use the Scanner class. A guide on how to use it here
Also if you want an output in your class you should use "return", and not have it as a parameter.
Do note that you haven't named your class yet, or specified the output type.
How it could look:
public String className(String input){
return input;
}

Java, seemingly randomly, started crashing on FileHandle.class.getResourceAsStream(path);

So, I'm working on a program that allows you to import animations in the form of JSON files into Minecraft, and, when working on a completely different part of the program, my import code stopped working.
I'm using eclipse, and this is how my import code looks:
package com.github.sam54123.mc_animation.utils;
import java.io.InputStream;
public class FileHandle
{
public static InputStream inputStreamFromFile(String path)
{
try
{
InputStream inputStream = FileHandle.class.getResourceAsStream(path);
return inputStream;
}
catch(Exception e)
{
e.printStackTrace();
}
return null;
}
}
new file
package com.github.sam54123.mc_animation.utils;
import java.io.File;
import java.io.InputStream;
import java.util.Scanner;
import org.json.JSONObject;
public class JSONUtils
{
public static String getJSONStringFromFile(String path)
{
// Open file
Scanner scanner;
try
{
InputStream in = FileHandle.inputStreamFromFile(path);
scanner = new Scanner(in);
// Get JSON as string without spaces or newlines
String json = scanner.useDelimiter("\\Z").next();
// Close file
scanner.close();
return json;
}
catch(Exception e)
{
System.out.println(e.getStackTrace());
return null;
}
}
public static JSONObject getJSONObjectFromFile(String path)
{
File file = new File(path);
if (!file.exists())
{
System.out.println("Invalid Path");
return null;
}
String string = getJSONStringFromFile(path);
return new JSONObject(string);
}
}
And I proceed to do some more fancy pampering of the file later on. This used to work reliably, until I made this in a completely different and un-related class:
String command = getCommand(object);
if (command != null && command.length() > 0)
{
commands.add(new AnimCommand(command, i));
}
And then it started throwing this error:
[Ljava.lang.StackTraceElement;#7852e922
Exception in thread "main" java.lang.NullPointerException
at java.io.StringReader.<init>(Unknown Source)
at org.json.JSONTokener.<init>(JSONTokener.java:94)
at org.json.JSONObject.<init>(JSONObject.java:406)
at com.github.sam54123.mc_animation.utils.JSONUtils.getJSONObjectFromFile(JSONUtils.java:47)
at com.github.sam54123.mc_animation.system.Animation.<init>(Animation.java:20)
at com.github.sam54123.mc_animation.testing.Tester.main(Tester.java:13)
I've double checked that the file hasn't changed, and I tried deleting that section of code, restarting Eclipse, the whole deal, and nothing seems to fix it. The code is even able to recognize that the file is valid using the File class, but nothing seems to change. Does anyone have some insight on how this might be fixed? Here is the rest of my code: https://github.com/Sam54123/mc-animation/
EDIT
Okay, I've just done some more debugging, and it looks like it's the
return new JSONObject(string);
on line 47 of the second file that's crashing. No idea why, as the risky stuff of reading a file off disk is okay.
EDIT 2
It looks looks like it's failing because
InputStream in = FileHandle.inputStreamFromFile(path);
is returning null, which makes sense because of the try catch statement
InputStream inputStream = FileHandle.class.getResourceAsStream(path);
is in. Why that's failing beats me though, because the validity of the file is verified elsewhere in the code. It also used to work, and I haven't changed anything about the layout of the files.
EDIT 3
Interesting, a couple System.out.printlns reveal the catch is not actually getting activated, and therefore getResourceAsStream() must actually be returning null. I've confirmed this by printing it out before I return it.

Reading multiple files in directory and printing specific content

What I am trying to achieve is basically a Java file which looks through a specific directory on the users computer, search all the files in the directory for specific word (in this case an email) and then at the end print them out.
The current script of which I have now, looks for all the files in a certain directory, prints out those file names. As well as that I have also figured out how to have that script search through one file for a specific word and then print it out. The only problem is that although it searches through that one file and gets that word/phrase it has to be given the full directory and file to work. I just want it to have a specific directory and then search all the files in it. I have tried doing this using the directory variable of which I have created to find all files, but it does not work when using that as the directory for the files to search through to find the word(s).
Here underneath is the part of my code which is used for the function I want. The actual function is called in my real script so don't worry about that as it is working. I have also just commented in the script what variable I want to work where.
package aProject;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
public class aScanner {
static String usernameMac = System.getProperty("user.name");
final static File foldersMac = new File("/Users/" + usernameMac + "/Library/Mail/V2"); // this is the right directory I want to look through
public static void listFilesForFolder(final File foldersMac) {
for (final File fileEntry : foldersMac.listFiles()) {
if (fileEntry.isDirectory()) {
listFilesForFolder(fileEntry);
try {
BufferedReader bReaderM = new BufferedReader(new FileReader("/Users/username/Library/Mail/V2/AosIMAP-/INBOX.mbox/longnumber-folder/Data/Messages/1.emlx")); //this is where I would like the foldersMac variable to work in, instead of this full directory
String lineMe;
while((lineMe = bReaderM.readLine()) != null)
{
if(lineMe.contains(".com"))
System.out.println(lineMe);
}
bReaderM.close();
}
catch (IOException e) {
}
} else {
System.out.println(fileEntry.getName());
}
}
}
}
I think this is what you're trying to achieve:
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
public class aScanner {
static String usernameMac = System.getProperty("user.name");
final static File foldersMac = new File("/Users/" + usernameMac + "/Library/Mail/V2");
public static void main(String[] args) throws IOException {
listFilesForFolder(foldersMac);
}
public static void listFilesForFolder(final File foldersMac) throws IOException {
for (final File fileEntry : foldersMac.listFiles()) {
if (fileEntry.isDirectory()) {
listFilesForFolder(fileEntry);
} else {
ArrayList<String> lines = new ArrayList<>();
try (BufferedReader bReaderM = new BufferedReader(new FileReader(fileEntry))) {
String lineMe;
while ((lineMe = bReaderM.readLine()) != null) {
if (lineMe.contains(".com")) {
lines.add(lineMe);
}
}
}
if (!lines.isEmpty()) {
System.out.println(fileEntry.getAbsolutePath() + ":");
for (String line : lines) {
System.out.println(" " + line.trim());
}
}
}
}
}
}
I think your problem lies around your recursion logic,
You go down recursively in the directory structure, you walk through you tree, but write out nothing cause of this if statement:
if (fileEntry.isDirectory()) {
listFilesForFolder(fileEntry);
...
}
Close that If statement earlier, then it should work.

regarding placing the txt file for java to read it right away

I want to read text and STORE it in a String variable ...
This code is working fine but i want to know where the txt file should be placed exactly for me to not specify the exact path. Since I'll be trying this code on various machines . so I hope you understood what I want.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.*;
public class Compress {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
String text="";
try {
text = new Scanner( new File("C:\\Users\\sandhya\\workspace\\PrefixFreeCodeChecker\\src\\poem.txt"), "UTF-8" ).useDelimiter("\\A").next();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
System.out.println(text+"");
}
}
Put your poem.txt file in your java project folder and change the path to this:
text = new Scanner( new File("poem.txt").....

Categories

Resources