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 :)
Related
I'm now writing a java class and want to read a txt file in, like this:
public class Myclass {
...
public static void main(String[] args) {
try{
File file = new File(args[0]);
Scanner scanner = new Scanner(file);
int [] array = new int [1000];
int i = 0;
while(scanner.hasNextInt())array[i++] = scanner.nextInt();}
catch (FileNotFoundException exp) {
exp.printStackTrace();}
}
...
}
And for example, use it like java Myclass input.txt. However when I use javac to compile it in Linux, erros throws:
error: cannot find symbol
catch (FileNotFoundException exp) {
^
symbol: class FileNotFoundException
location: class Myclass
That's weird since name of input file hasn't even been passed in. I've tried File file = new File('input.txt'); and it also throws this error, so I don't know what's wrong (System.out.println(new File('input.txt').getAbsolutePath());will print out the correct and existed path).
You need to add correct imports at the begining of a class:
import java.io.FileNotFoundException;
public class Myclass {...
i think you have to compile your class using the following command
javac com/Trail.java
javac <package-name1>/<package-name2>/<classname.java>
then run the following command
java com.Trail test.txt
the you have to ensure test.txt place then it will works for you, let me recommand you the following answer of the question it helps me a lot to run your code here and here
for where you should put your file
note:
try to declare public static void main(String args[]) throws FileNotFoundException
please you have to be inside folder of file which you want to compile
It looks like you did not import the class FileNotFoundException.
Adding a import java.io.FileNotFoundException at the top of your file should resolve the issue.
Assuming all the imports are alright, the next most likely cause is the txt file is not there. You have to put your txt file at the same folder that there are folders like "src", "dist" and "build".
I've figured it out!
declare main like this:
public static void main(String args[]) throws FileNotFoundException{
...
Try to put the location of file that you want to read, something like this:
File file = new File("C:\\text.txt");
Full example:
public static void main(String[] args)
{
File file = new File("C:\\text.txt");
Scanner sc = new Scanner(file);
while (sc.hasNextLine())
System.out.println(sc.nextLine());
}
I just want some files to be read and written in my Java program. So I use java.security.SecurityManager to manage this, but it seems unsatisfactory.
The Main.java file is below
import java.io.*;
import java.util.*;
public class Main {
static private final String INPUT = "in.txt";
public static void main(String args[]) throws Exception {
FileInputStream instream = null;
BufferedReader reader = new BufferedReader(new FileReader(INPUT));
String tempString = null;
while ((tempString = reader.readLine()) != null) {
System.out.println(tempString);
}
}
}
and the file /opt/java.policy like below
grant {
permission java.io.FilePermission "./out.txt", "write";
};
Then I run
java -Xss64m -Xms16m -Xmx512m -Djava.security.manager -Djava.security.policy=/opt/java.policy Main
But there are no errors, the output is what the in.txt is. I tried other file and got the same result. Why does this happen?
From the Javadoc:
Please note: Code can always read a file from the same directory it's in (or a subdirectory of that directory); it does not need explicit permission to do so.
Not that this is well-specified. Code isn't 'in' a directory: it is executed from a current working directory, and this appears to be what is meant.
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.
I'm trying to load a file from resources/ path using
getClassLoader().getResourceAsStream("file.LIB")
but the method always returns null, unless I rename the file into another extension, say ".dll".
I've looked into the official Java documentation, but to no avail.
Why does the method acts strange on that file type?
Note: I'm using JDK 1.8.0_111 x86 (due to constraints on that lib file, which only works well with a 32-bit JVM)
It does works for me, you need to be sure what exactly you are doing with lib file.
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
public class FileHelper {
public String getFilePathToSave() {
Properties prop = new Properties();
String filePath = "";
try {
InputStream inputStream =
getClass().getClassLoader().getResourceAsStream("abc.lib");
prop.load(inputStream);
filePath = prop.getProperty("json.filepath");
} catch (IOException e) {
e.printStackTrace();
}
return filePath;
}
public static void main(String args[]) {
FileHelper fh = new FileHelper();
System.out.println(fh.getFilePathToSave());
}
}
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").....