I'm currently trying to write a program that will read in a file line by line and add each line to an arrayList. My other function is supposed to sort the items from that buffer, then write them to a text file. However, I keep getting a FileNotFoundException, even when my file is sitting in the src directory, as well as the directory with my .class file. My code is as follows
public static ArrayList<String> readDictionary(String filename,
ArrayList<String> buffer) throws IOException, FileNotFoundException {
File f = new File(filename);
Scanner fileIn = new Scanner(f);
//Scanner fileIn = new Scanner(new File(filename));
boolean add = true;
while (fileIn.hasNextLine() == true) {
for (String s : buffer) {
if (fileIn.nextLine().equals(s)) {
add = false;
}
}
if (add == true) {
buffer.add(fileIn.nextLine());
}
add = true;
}
fileIn.close();
return buffer;
}
public static void writeDictionary(String filename, ArrayList<String> buffer) throws IOException, FileNotFoundException {
File f = new File(filename);
Collections.sort(buffer, String.CASE_INSENSITIVE_ORDER);
Path file = Paths.get(filename);
Files.write(file, buffer);
}
public static void main(String[] args) throws IOException, FileNotFoundException{
ArrayList<String> buffer = new ArrayList<>();
readDictionary("inputtest.txt", buffer);
}
Exception in thread "main" java.io.FileNotFoundException: inputtest.txt (The system cannot find the file specified)
at java.io.FileInputStream.open0(Native Method)
at java.io.FileInputStream.open(FileInputStream.java:195)
at java.io.FileInputStream.<init>(FileInputStream.java:138)
at java.util.Scanner.<init>(Scanner.java:611)
at UltimateDictionary.readDictionary(UltimateDictionary.java:18)
at UltimateDictionary.main(UltimateDictionary.java:46)
I tested this program by setting filename equal to "inputtest.txt", and that file is sitting in my src directory with the .java file, but it still throws the error. Also, how can I close the files? f.close() gives me an error.
The file in your src or .class directory, could only mean that the file is in classpath, while new File(filename); search the current working directory. To search classpath, change readDictionary method, after File f = new File(filename); add:
if (!f.exists()) {
URL url = <yourclassname>.class.getResource(filename);
if (url != null)
f = new File(url.getPath());
}
you have to use yourclassname.class because the method is static. Should work also:
if (url == null)
url = ClassLoader.getSystemResource(filename);
Related
I have a Jar file which has many excel sheets inside it. I want to access the excels sheets while running the Jar file and copy somewhere. How can I do that ?
You can access the Excel sheets as resources in the classpath:
Class.getResourceAsStream("/excelfiles/myfile.xlsx");
For reading Excel sheets in java you can use Apache POI library
If you only want to copy the files to an output folder (without understanding Excel, you can just read the resource as an InputStream and write it to a a FileOutputStream.
The issue is resolved. I used below code to access the excels inside jar and copy excels outside my Jar
public static void main(String[] args) throws IOException {
final String classPath = "Path_Of_Jar/abc.jar";
JarFile jarFile = new JarFile (classPath);
String copyFolderExcel="Path to copy excels";
File excelFolderFile = new File (copyFolderExcel);
excelFolderFile.mkdir();
Enumeration<JarEntry> e = jarFile.entries ();
while (e.hasMoreElements ()) {
JarEntry entry = (JarEntry) e.nextElement ();
if (entry.getName ().contains ("excelFiles/")) {
String name = entry.getName ();
if(name.contains (".xlsx")) {
copyExcel(jarFile,name,copyFolderExcel);
}
}
}
jarFile.close ();
}
private static void copyExcel(JarFile jarFile, String file,String updatedFolder) throws IOException {
String[] outputFileName = file.split ("/");
String finalName = outputFileName[outputFileName.length-1];
JarEntry entry = (JarEntry) jarFile.getEntry(file);
InputStream input = jarFile.getInputStream(entry);
OutputStream output = new FileOutputStream (updatedFolder+"/"+finalName);
try {
byte[] buffer = new byte[input.available ()];
for (int i = 0; i != -1; i = input.read (buffer)) {
output.write (buffer, 0, i);
}
} finally {
input.close();
output.close();
}
}
}
In my program I suppose to copy a directory to another directory with java. I did it but the only problem is that for the directories that are inside the source directory get copied but not the file inside them. Why?
This is the assigment:
Ask the user for the source directory and a destination. The source is the directory to be copied; the destination is the directory that will be the parent of the new copy.
First your program should make a new directory in the new location with the same name as the source directory. (You may need to do something special for root directories if you are copying an entire disk. A root directory has no parent directory, and often, no name.)
Then your program should create an array with File class objects for each item in the contents of the source directory, similar to what was done in DirectoryListDemo.
Next , it should iterate the array, and for each item in the array,
if it is a file, copy the file to the new directory using the copyFile() method taken from CopyFileDemoE.
if it is a directory, recursively call this method to copy the directory and all of its contents.
Here is the code:
package com.company;
import java.io.*;
import java.util.Scanner;
public class Main {
public static void main(String[] args) throws Exception {
Scanner src = new Scanner(System.in);
System.out.println("Enter name of source directory to copy from: ");
String sourceFile= src.nextLine();
System.out.println("Enter name of destination directory to copy the files into: ");
String destinationFile = (src.nextLine()+"/"+sourceFile);
isDirFile(sourceFile, destinationFile);
}
public static void isDirFile(String source, String dest) throws Exception{
File sourceFile = new File ("C:/"+source);
File dirFile = new File (dest, new File(source).getName());
dirFile.mkdirs();
File[] entries;
if (dirFile.exists()){
if (sourceFile.isDirectory()){
entries = sourceFile.listFiles();
assert entries != null;
for (File entry:entries){
if(entry.isFile()){
copyFile(entry.getAbsolutePath(),dest);
}
else{
isDirFile(entry.getAbsolutePath(),dest);
}
}
}
}
else{
System.out.println("File does not exist");
}
}
public static void copyFile(String source, String destination) throws Exception{
File sourceFile;
File destFile;
FileInputStream sourceStream;
FileOutputStream destSteam;
BufferedInputStream bufferedSource = null;
BufferedOutputStream bufferedDestination = null;
try{
sourceFile = new File(source);
destFile = new File (destination, new File(source).getName());
sourceStream = new FileInputStream(sourceFile);
destSteam = new FileOutputStream(destFile);
bufferedSource = new BufferedInputStream(sourceStream, 8182);
bufferedDestination = new BufferedOutputStream(destSteam, 8182);
int transfer;
System.out.println("Beginning file copy: ");
System.out.println("\tcopying "+ source);
System.out.println("\tto "+destination);
while ((transfer = bufferedSource.read()) != -1){
bufferedDestination.write(transfer);
}
}
catch (IOException e){
e.printStackTrace();
System.out.println(" An unexpected I/O error occurred.");
}
finally {
if(bufferedSource != null){
bufferedSource.close();
}
if(bufferedDestination != null){
bufferedDestination.close();
}
System.out.println("Files closed. Copy complete.");
}
}
}
Iam trying to add a path (string) over an editfield in class main, the path will be taken to another class extract. After this I want to read the file with FileReader, but I got some error: file not found.
So I does some test:
I wrote the path directly in the FileReader -> everything Okay
I wrote a function File named sFile to get the path from class main and try to find the file behinde the path (exists). The file could be found but if FileReader trying to load the file got the same error
Code:
File sFile = new File(path);
if (sFile.exists()){
System.out.println("Found.");
System.out.println(sFile.getAbsolutePath());
try{
FileReader file = new FileReader(sFile); //db10916358-hp.sql (test file)
String[] fReadTmp = new String[10240000];//Just for testing
BufferedReader br = new BufferedReader(file);
String read = br.readLine();//Read a line
I found the error, it was an other File function which creates some files from the extract.
It was so simple, sorry for that.
Thanks for your time!
Try this snippet of code its work correctly
public static void readFile(String path) throws FileNotFoundException, IOException{
File file = new File(path);
if(file.exists())
{
FileReader fileReader = new FileReader(file); //db10916358-hp.sql (test file)
BufferedReader br = new BufferedReader(fileReader);
String read = br.readLine();//Read a line
}
else
{
System.out.print("Not Found");
}
}
I have a method that takes source address, destination address and an ArrayList, then it goes through the giver Source folder and check each file with the ArrayList items and if they have the same name, then it copies the the destination with the exact same folder structure (so it makes folders in needed). All works till here. But it gives error if the item of the ArrayList is a folder name. Some how It can't find that folder, and comes up with errors.
Here is my code:
public class Syncer {
public static void main(String[] args) {
File source = new File("D:\\Documents\\A X");
File destination = new File("D:\\Documents\\A X Sample");
ArrayList<String> list = new ArrayList<String>();
list.add("third");
folderCrawler(source, destination, list);
}
public static void folderCrawler(File src, File dest, ArrayList<String> filesToCopy){
if(src.isDirectory()){
String[] children = src.list();
for(String file:children){
if(filesToCopy.contains(file)){
File from = new File(src, file);
File to = new File(dest, file);
dest.mkdirs();
try{
copy(from, to);
}catch(IOException e){
e.printStackTrace();
System.exit(0);
}
}
else{System.out.println("Not Found");}
}
for (int i=0; i<children.length; i++){
folderCrawler(new File(src, children[i]), new File(dest, children[i]), filesToCopy);
}
}
}
public static void copy(File src, File dest) throws IOException{
InputStream in = new FileInputStream(src);
OutputStream out = new FileOutputStream(dest);
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
System.out.println("Copied: " + src.getName());
in.close();
out.close();
}
}
It does compile and goes down the list till it finds the array item same as the current source, and then stops.
Error:
java.io.FileNotFoundException: D:\Documents\A X\folder2\tohi\third (Access is denied)
at java.io.FileInputStream.open(Native Method)
at java.io.FileInputStream.<init>(FileInputStream.java:138)
at syncer.Syncer.copy(Syncer.java:61)
at syncer.Syncer.folderCrawler(Syncer.java:45)
at syncer.Syncer.folderCrawler(Syncer.java:55)
at syncer.Syncer.folderCrawler(Syncer.java:55)
at syncer.Syncer.main(Syncer.java:31)
In my other mathchine I get same error but it is (Is a directory) instead of (Access denied).
So any idea to make it work even if a folder is given. So it will copy the folder with its inner files ?
Sorry, I don' have enough rep to comment.
Have a look at apache commons FileUtils. They have a lot of copy functions so you don't have to implement them yourself.
I get this exception when I try to read from a file:
ERROR:
Exception in thread "main" java.io.FileNotFoundException: newfile.txt (No such file or directory)
at java.io.FileInputStream.open(Native Method)
at java.io.FileInputStream.<init>(FileInputStream.java:138)
at java.util.Scanner.<init>(Scanner.java:611)
at Postal.main(Postal.java:19)
import java.util.Scanner;
import java.io.*;
public class Postal {
public static void main(String[] args) throws Exception {
/*** Local Variables ***/
String line;
Scanner filescan;
File file = new File("newfile.txt");
filescan = new Scanner(file);
userInfo book = new userInfo();
/*** Loop through newfile.txt ***/
while (filescan.hasNext()) {
line = filescan.nextLine();
book.addNew(line);
}
book.print(0);
}
}
The class Scanner uses a FileInputStream to read the content of the file.
But it can't find the file so a exception is thrown.
You are using a relative path to the file, try out an absolute one.
Use this instead:
File file = new File(getClass().getResource("newfile.txt"));
Provide an absolute path the location where you want to create the file. And check that user has rights to create file there. One way to find the path is:
File f = new File("NewFile.txt");
if (!f.exists()) {
throw new FileNotFoundException("Failed to find file: " +
f.getAbsolutePath());
}
Try this to open file:
File f = new File("/path-to-file/NewFile.txt");