I have a homework to do and I don't know how to get started. I have to read from an external text file the paths of some random folders. I must make the paths for this folders available even I change the computer.
Then I have to output in the console the number of mp3 files found in every each folder.
My big problem is that I don't know how to make those paths work for every computer on which I run the program and also I don't know how the filter the content.
LATER EDIT: I've managed to write some code. I can search now for the mp3, but... can someone help me with this: how can i add a new path to the txt file from keyboard and also how can i remove an entire line from it?
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
public class Main {
public static void main(String[] args) throws IOException {
String ext = ".mp3";
BufferedReader br = new BufferedReader(new FileReader("Monitor.txt"));
for (String line; (line = br.readLine()) != null;) {
findFiles(line, ext);
}
br.close();
}
private static void findFiles(String dir, String ext) {
File file = new File(dir);
if (!file.exists())
System.out.println(dir + " No such folder folder");
File[] listFiles = file.listFiles(new FiltruTxt(ext));
if (listFiles.length == 0) {
System.out.println(dir + " no file with extension " + ext);
} else {
for (File f : listFiles)
System.out.println("Fisier: " + f.getAbsolutePath());
}
}
}
import java.io.File;
import java.io.FilenameFilter;
public class FiltruTxt implements FilenameFilter{
private String ext;
public FiltruTxt(String ext){
this.ext = ext.toLowerCase();
}
#Override
public boolean accept(File dir, String name) {
return name.toLowerCase().endsWith(ext);
}
}
I think that with "available even I change the computer" mean that you need to read the path from the file and not hard code it on your program so if you run in other computer you only need to change the text file and not the program.
But as #André Stannek had said in his comment, you must add to your question what have you tried and what is the exact programming problem you are facing.
When you face a problem, try to divide it in individual and more small problems. For example:
How to read a line from the console?
How to write a new line to a file?
Then try to search for a solution (if you can't think in one). For example in stack overflow, google and of course in the official documentation.
The official documentation:
http://docs.oracle.com/javase/tutorial/essential/io/index.html
Some questions in stackoverflow:
Read multiple lines from console and store it in array list in Java?
Read string line from console
How do I add / delete a line from a text file?
How to add a new line of text to an existing file in Java?
Or this links from Internet:
http://www.msccomputerscience.com/2013/01/write-java-program-to-get-input-from.html
This is the portal of the Java tutorials that you will found very useful when you are learning: http://docs.oracle.com/javase/tutorial/index.html
Related
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 am new in Java and I have a question regarding the method readAlllines for the class Files. The file "Testfile.txt" is saved in the same directory as my Java class changeFiles. I want to read the lines out of it.
Here is my example code:
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
public class changeFiles {
public static void main(String[] args) {
File temp =new File("Testfile.txt");
Path p = temp.toPath();
try{
List<String> zeilen = Files.readAllLines(p);
for(String line : zeilen){
System.out.println(line);
}
} catch (IOException e) {
System.out.println(e);
}
}
}
Unfortunately, the method can't find the file. How do I get the correct path to my file in readAllLines?
You're trying to get file from working directory, check yours printing this in some way
System.getProperty("user.dir")
Place "Testfile.txt" there, run and enjoy.
Another solution will be put folder when reading file using File(folder, file) constructor:
// imagine your file is placed in: c:\tmp\Testfile.txt
final String folder = "C:\\tmp\\";
File temp = new File(folder, "Testfile.txt");
Or maybe merge both:
final String folder = System.getProperty("user.dir");
File temp = new File(folder, "Testfile.txt");
Java class location is not the same as current directory.
For example current directory is something like:
C:\Users\userName\project (This is where txt file shoud be)
And java class is something like C:\Users\userName\project\src\packageName\Java.java
to find out what the current directory is you can run: System.getProperty("user.dir")
I am trying to read from a text file. I have the file created, it only needs to have one record, but it could have more. I keep getting errors. I am a Geography student, not an IT guy, I am hoping to figure out the next step once I get this. Here is my example, that doesn't work:
import java.io.*;
import java.util.*;
import java.lang.*;
public class Driver
{
public static void main(String[] args) throws IOException
{
File data;
String fileName = null; // User input file name
Scanner input;
input = new Scanner(System.in);
System.out.println("Enter file name (ie: text.txt): ");
data = new File(input.next());
Scanner read;
read = new Scanner(data);
fileName = read.nextLine();
System.out.println(fileName);
}
}
I believe an error that you are having is not referencing the correct place when trying to access the file. If you just type in example.txt, the java compiler has no idea where to find this file.
Try this:
Right click under the package
Create new folder, and call it 'texts'
Open file explorer
Paste all your .txt files into this new folder 'texts'
Replace fileName = read.nextLine(); with fileName = "texts/" + read.nextLine();
After this you should be good to go!
You have two options.
Put text.txt file in same folder where your class files are.
Get full path of the file from user like C:\text.txt.
It'll run.
I had a lecture today on inputting and outputting but it didn't really seem to explain where the text file is etc..
here is my code:
package inputoutput;
import java.util.*;
import java.io.*;
public class input {
public static void main(String[] args) throws FileNotFoundException {
String name;
int lineCount = 0;
File input = new File("lab1task3.txt");
Scanner in = new Scanner(input);
while(in.hasNextLine()){
lineCount++;
}
System.out.println(lineCount);
}
}
I get a file not found exception but the text file is in the same folder as the program?
Please first read up on the difference between relative and absolute paths. An absolute path is:
C:\Users\Ceri\workspace1\inputoutput\src\inputoutput\lab1task3.txt
A relative path would be just "lab1task3.txt", which is what is given. That means that lab1task3.txt can be found relative to the working directory (e.g if the working directory was "C:\Users\Ceri\workspace1\inputoutput\src\inputoutput\" then it would find it).
However, you could also use an absolute path, but remember that doing so means that it will only work if a file is in the same place on the machine running it. E.g, if you submit with "C:\Users\Ceri\workspace1\inputoutput\src\inputoutput\" in your code then it will only work if someone else has that same file and location on their computer. Please note that if this is an assignment, the module convenor/marker probably does not have afolder called C:\Users\Ceri.... If you submit your work using a relative path, anyone using your code just needs to make sure the file is relatively in the same place (e.g in the same folder).
If this doesn't matter, you need to escape the back slash characters with another back slash in the path. This should work:
package inputoutput;
import java.util.*;
import java.io.*;
public class input {
public static void main(String[] args) throws FileNotFoundException {
String name;
int lineCount = 0;
File input = new File("C:\\Users\\Ceri\\workspace1\\inputoutput\\src\\inputoutput\\lab1task3.txt");
Scanner in = new Scanner(input);
while(in.hasNextLine()){
lineCount++;
}
System.out.println(lineCount);
}
}
I notice you are using eclipse. Your "working directory" is your workspace. Therefore you want to move your file to:
C:\Users\Ceri\workspace1\inputoutput\lab1task3.txt
This should work for you using a "relative" path which you had in your opening post.
You're confusing class file location and the "user's working directory", the latter being what Java uses to determine the root of the file path (unless absolute paths are needed), and you can find its location easily via:
System.out.println(System.getProperty("user.dir"));
I advise you to forgo use of files altogether when all you need to do is read in data, and instead get the text file as a program resource:
// where you swap the name of your class for MyClass
InputStream fileResource = MyClass.class.getResourceAsStream("myFile.txt");
Scanner scanner = new Scanner(inputStream);
Note that if you must use a File, then find out what the user's working directory is, as shown above, and then tailor your file path so that it is relative to this working directory.
Try:
File file = new File("src/inputoutput/lab1task3.txt");
My guess is that your current working directory is not the same place as the project location. If your working directory were, the file would definitely be found if it does indeed have that name.
To workaround this issue you can always be using a InputStream instead, like so:
InputStream inputStream = new InputStream("lab1task3.txt");
Scanner scanner = new Scanner(inputStream);
If you want to see your current working directory you can use something like this:
public class JavaApplication1 {
public static void main(String[] args) {
System.out.println("Working Directory = " +
System.getProperty("user.dir"));
}
}
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'.