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'.
Related
I'm trying to move files using this java code and it can locate the file but not move it, just deletes the directory I'm moving it to.
public void ch() throws Exception{
if (FC.showOpenDialog(null) == JFileChooser.APPROVE_OPTION){
java.io.File file = FC.getSelectedFile();
Scanner input = new Scanner(file);
System.out.println(file);
Path source = Paths.get(file + "");
Path target = Paths.get("C:\\Users\\Marcus\\Desktop\\2");
try {
Files.move(source, target, REPLACE_EXISTING);
} catch (IOException e){
System.out.println("Failed to move the file");
}
}else{
System.out.println("?");
}
}
Add the file name at the end of your destination path, like below:
You could move files with File.ranameTo() method, like this:
file.renameTo(new File("C:\\Users\\Marcus\\Desktop\\2\\"+file.getName()));
In your example:
public void ch() throws Exception{
if (FC.showOpenDialog(null) == JFileChooser.APPROVE_OPTION){
java.io.File file = FC.getSelectedFile();
try {
file.renameTo(new File("C:\\Users\\Marcus\\Desktop\\2\\"+file.getName()));
} catch (Exception e){
System.out.println("Failed to move the file");
}
}else{
System.out.println("?");
}
}
If you want to use Files.move(), your target path should probably be the full path of the target file, not the destination directory where you want to place it.
Path target = Paths.get("C:\\Users\\Marcus\\Desktop\\2\\" + source.getName());
You should use Files.copy() instead of Files.move().
I strongly recommend the use of a third party tool such as Apache Commons IO's FileUtil class for this type of operation.
For example: FileUtil.moveFileToDirectory
Using these types of utilities saves you from many problems you aren't even aware are lurking. Yes, there are limitations to these common utils, but the benefits usually outweigh them in simple cases.
Google Guava is also an option, but I've got less experience there.
Your code is close but there a couple of potential issues. Before I start, I should say that I'm using a Mac (hence the path change), so while this is working for me, there may be some underlying permission issue on your system I can't account for.
1) You aren't using the name of the file you want to move to. You're using the directory you want to move the file to. That's a fair assumption, but you need to make it the fully qualified path and file name.
2) You are creating a Scanner to the to file but not using it. This probably doesn't really matter, but it's best to eliminate unnecessary code.
3) You don't validate the path that was created by getting the Path instance returned from Files.move().
Here is my example code. I tested it and it worked fine. Again, I'm using a Mac, so take that into account.
public void moveFile(){
JFileChooser fc = new JFileChooser("/");
if (fc.showOpenDialog(null) == JFileChooser.APPROVE_OPTION){
File file = fc.getSelectedFile();
System.out.println("Chosen File: " + file.getAbsolutePath());
String newFileName = System.getProperty("user.home")+File.separator+file.getName();
System.out.println("Attempting to move chosen file to destination: " + newFileName);
Path target = Paths.get(newFileName);
try {
Path newPath = Files.move(file.toPath(), target, REPLACE_EXISTING);
System.out.println("Path returned from move: " + newPath);
} catch (IOException e){
// Checked exceptions are evil.
throw new IllegalStateException("Unable to move the file: " + file.getAbsolutePath(),e);
}
}
}
The output from one of the tests:
Chosen File: /Users/dombroco/temp/simpleDbToFileTest1.txt
Attempting to move chosen file to destination: /Users/dombroco/simpleDbToFileTest1.txt
Path returned from move: /Users/dombroco/simpleDbToFileTest1.txt
Im trying to write a function that will take a string, then open a file with that string name and read the text. I know how to do this, but im having trouble with the fact that my text files are not saved in the same place as my java file.
It looks like this.
Project name/src/program.java
Project name/resources/text.txt
Im using the File class, but dont know what to put in the File constructor to open to the right place.
ie. File store = new File(xxxxxxxxxtext.txt)
Help me out with what goes in front of the file name please. Also, this is java 6 and im on windows 8.
This is my code:
public static void areaSearch(String a) {
Scanner reader = null;
try {
reader = new Scanner(new File("../resources/" + a+ ".txt"));
}
catch (Exception e) {
System.out.println("File: " + a +" not opended...");
}
Use relative path if it's on an easy relative path from your project folder:
File file = File("../resources/text.txt");
Or use absolute path:
File file = File("C:\\abcfolder\\text.txt");
Read documentation. There are more, than 1 constructor for File class. Use:
public File(File parent, String child)
I'm very new at coding java and I'm having a lot of difficulty.
I'm suppose to write a program using bufferedreader that reads from a file, that I have already created named "scores.txt".
So I have a method named processFile that is suppose to set up the BufferedReader and loop through the file, reading each score. Then, I need to convert the score to an integer, add them up, and display the calculated mean.
I have no idea how to add them up and calculate the mean, but I'm currently working on reading from the file.
It keeps saying that it can't fine the file, but I know for sure that I have a file in my documents named "scores.txt".
This is what I have so far...it's pretty bad. I'm just not so good at this :( Maybe there's is a different problem?
public static void main(String[] args) throws IOException,
FileNotFoundException {
String file = "scores.txt";
processFile("scores.txt");
//calls method processFile
}
public static void processFile (String file)
throws IOException, FileNotFoundException{
String line;
//lines is declared as a string
BufferedReader inputReader =
new BufferedReader (new InputStreamReader
(new FileInputStream(file)));
while (( line = inputReader.readLine()) != null){
System.out.println(line);
}
inputReader.close();
}
There are two main options available
Use absolute path to file (begins from drive letter in Windows or
slash in *.nix). It is very convenient for "just for test" tasks.
Sample
Windows - D:/someFolder/scores.txt,
*.nix - /someFolder/scores.txt
Put file to project root directory, in such case it will be visible
to class loader.
Place the scores.txt in the root of your project folder, or put the full path to the file in String file.
The program won't know to check your My Documents folder for scores.txt
If you are using IntelliJ, create an input.txt file in your package and right click the input.txt file and click copy path. You can now use that path as an input parameter.
Example:
in = new FileInputStream("C:\\Users\\mda21185\\IdeaProjects\\TutorialsPointJava\\src\\com\\tutorialspoint\\java\\input.txt");
Take the absolute path from the local system if you'r in eclipse then right-click on the file and click on properties you will get the path copy it and put as below this worked for me In maven project keep the properties file in src/main/resources `
private static Properties properties = new Properties();
public Properties simpleload() {
String filepath="C:/Users/shashi_kailash/OneDrive/L3/JAVA/TZA/NewAccount/AccountConnector/AccountConnector-DEfgvf/src/main/resources/sample.properties";
try(FileInputStream fis = new FileInputStream(filepath);) {
//lastModi = propFl.lastModified();
properties.load(fis);
} catch (Exception e) {
System.out.println("Error loading the properties file : sample.properties");
e.printStackTrace();
}
return properties;
}`
i am trying to create a text file in a folder (called AMCData). The file is called "File" (for the sake of this example).
I have tried using this code:
public static void OpenFile(String filename)
{
try
{
f = new Formatter("AMCData/" + filename + ".txt");
}
catch(Exception e)
{
System.out.println("error present");
}
}
But before i get the chance to even place any text in it, the catch keeps being triggered..
Could anyone inform me why this is occuring?
more information:
The folder does not exist, i was hoping it would automatically create it
If it doesn't automatically create folders, could you please link me to how to do so?
You're right, a Formatter(String) constructor needs the file to be present or createable. The most likely reason why a file cannot be created is that it references a folder that itself doesn't exist, so you should use the File.mkdirs() method, like this:
new File("AMCData").mkdirs();
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")