Reading from a text file throws exception - java

So I've used DataInputStream, FileInputStream, BufferInputStream, FileReader, BufferedReader, Scanner, you name it. They all throw FileNOtFoundException or CorruptedStreamException.
the exception
java.io.FileNotFoundException: java.io.FileReader#253498.data (The system cannot find the file specified)
gets thrown on the line where the FileReader is initialized with the filename "Accounts.txt", which is a file that i HAVE initialized, in the bin, with the text needed in it.
import java.io.*;
import java.util.ArrayList;
/**
* Class to load account files
*/
public class AccountLoader {
/**
* Add an account file
* #param newAccount
*/
public static void addAcountFile(Account newAccount) {
try {
PrintWriter out = new PrintWriter(new File("Accounts.txt"));
out.print(" " + newAccount.getOwner().getName());
System.out.println("saved account " + newAccount.getOwner().getName());
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
public static ArrayList<Account> loadAccountsList() throws EOFException, IOException, ClassNotFoundException{
ArrayList<Account> accounts = new ArrayList();
FileReader load = new FileReader("Accounts.txt");
String file = load.toString();
String[] accountsload = file.split(" ");
for (String string : accountsload){
accounts.add(loadAccount(string + ".data"));
}
load.close();
return accounts;
}
public static void save(Account account) {
String filename = account.getOwner().getName() + ".data" ;
if (filename != null) {
try {
FileOutputStream fos = new FileOutputStream(filename);
ObjectOutputStream out = new ObjectOutputStream(fos);
out.writeObject(account);
out.flush();
out.close();
}
catch (IOException e) { System.out.println(e); }
}
}
public static Account loadAccount(String filename) {
Account newAccount = null;
if (filename != null) {
try {
FileInputStream fis = new FileInputStream(filename);
ObjectInputStream in = new ObjectInputStream(fis);
newAccount = (Account)in.readObject();
in.close();
}
catch (Exception e) { System.out.println(e); }
}
return newAccount;
}
}

You probably need to put the text file in the "project root" folder (the one that contains src and bin), not the bin folder. If you're running this from Eclipse that's definitely what you need to do, since the context for Java projects run from Eclipse is always the Eclipse project folder for that project.
When you ask Java to open a file by name without giving it a path, the JVM will look for the file in its current working directory. The current working directory changes depending on how you run the program, and in your case it looks like the "bin" folder is not your current working directory.

Try moving the text file to some other folders. One folder out of the bin folder is probably the right location.

If you are using command line, put the file in the folder from where you are running the java command and add . in the CLASSPATH as
set CLASSPATH=%CLASSPATH%;.
and then run your java program.
If you are using eclipse, try putting the file in root folder of the project or use the relative path with respect to root folder.

Related

Printing contents of an imported class to console in java

I'm programming in an online IDE (it is studio.code.org) (For a programming course). I would like to switch to a local IDE, but the online IDE uses some imports that are unavailable to download, but can be used in the code that has been written in the online IDE. This is in java. To make this a more general form of question that applies to (and will help) most people:
This is in java. I'm trying to print the contents of a file out in the console whose path is unknown, but is used as an import. Is it possible? If so, what code do I need to run to print the file out in console (from where I can copy paste it and use it elsewhere).
Here's the source code for something I tried to make this happen (but it didn't work, I'll show what output I got from the console below the code):
import java.io.*;
import org.code.neighborhood.Painter;
public class MyNeighborhood {
public static void main(String[] args) {
try {
Class<?> cls = Class.forName("org.code.neighborhood.Painter");
String fileName = cls.getName().replace('.', File.separatorChar) + ".class";
File file = new File(fileName);
System.out.println("File path: " + file.getAbsolutePath());
FileInputStream fis = new FileInputStream(file);
byte[] buffer = new byte[(int) file.length()];
fis.read(buffer);
fis.close();
System.out.println(new String(buffer));
} catch (Exception e) {
e.printStackTrace();
}
}
}
Output from console:
[JAVALAB] Connecting...
[JAVALAB] Compiling...
[JAVALAB] Compilation successful.
[JAVALAB] Running...
File path: /tmp/org/code/neighborhood/Painter.class
As you may have noticed I have found a file, but it is empty, although I know that the real file that is being imported is certainly not empty.
I do have read access to the system as well since I am able to navigate the root folder by using the code below:
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
public class Main {
public static void main(String[] args) {
boolean readContent = false; // change this to true to read file content, false to read file names
File directory = new File("/");
if (readContent) {
String fileName = "";
readFileContent(directory, fileName);
} else {
String[] fileNames = readFileNames(directory);
if (fileNames == null) {
System.out.println("Directory not found.");
} else {
System.out.println("Files in the directory:");
for (String fileName : fileNames) {
File file = new File(directory, fileName);
if (file.isDirectory()) {
System.out.println("Directory: " + fileName);
} else if (file.isFile()) {
System.out.println("File: " + fileName);
}
}
}
}
}
private static void readFileContent(File directory, String fileName) {
File file = new File(directory, fileName);
if (file.isFile()) {
try (FileReader reader = new FileReader(file)) {
int c;
while ((c = reader.read()) != -1) {
System.out.print((char) c);
}
} catch (IOException e) {
System.out.println("Error reading file: " + e.getMessage());
}
} else {
System.out.println("File not found.");
}
}
private static String[] readFileNames(File directory) {
if (directory.isDirectory()) {
return directory.list();
}
return null;
}
}

How to access and read a .txt file from a runnable jar

How can i load a text file with a runnable .jar file, It works fine when it's not jarred but after i jar the application it can't locate the file. Here's what i'm using to load the text file.
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
public class PriceManager {
private static Map<Integer, Double> itemPrices = new HashMap<Integer, Double>();
public static void init() throws IOException {
final BufferedReader file = new BufferedReader(new FileReader("prices.txt"));
try {
while (true) {
final String line = file.readLine();
if (line == null) {
break;
}
if (line.startsWith("//")) {
continue;
}
final String[] valuesArray = line.split(" - ");
itemPrices.put(Integer.valueOf(valuesArray[0]), Double.valueOf(valuesArray[1]));
}
System.out.println("Successfully loaded "+itemPrices.size()+" item prices.");
} catch (final IOException e) {
e.printStackTrace();
} finally {
if (file != null) {
file.close();
}
}
}
public static double getPrice(final int itemId) {
try {
return itemPrices.get(itemId);
} catch (final Exception e) {
return 1;
}
}
}
Thanks for any and all help.
There are two reasons for this. Either the file is now embedded within the Jar or it's not...
Assuming that the file is not stored within the Jar, you can use something like...
try (BufferedReader br = new BufferedReader(new InputStreamReader(PriceManager.class.getResourceAsStream("/prices.txt")))) {...
If the prices.txt file is buried with the package structure, you will need to provide that path from the top/default package to where the file is stored.
If the file is external to the class/jar file, then you need to make sure it resides within the same directory that you are executing the jar from.
if this is your package structure:
Correct way of retrieving resources inside runnable or.jar file is by using getResourceAsStream.
InputStream resourceStream = TestResource.class.getResourceAsStream("/resources/PUT_Request_ER.xml");
If you do getResource("/resources/PUT_Request_ER.xml"), you get FileNotFoundException as this resource is inside compressed file and absolute file path doesn't help here.

java file.exists doesn't find my file

I'm using Windows7. I've written this simple java code:
package filetest;
import java.io.File;
public class FileTest {
public static void main(String[] args) {
File myfile = new File("C://test//test.txt");
if (myfile.exists()) {
System.out.println("file exists");
} else {
System.out.println("file doesn't exist");
}
}
}
The file DOES exists in C:/test/test.txt, but the answer is that file doesn't exists.
Why?
EDITED:
I've changed the code and it still doesn't find the file, but now it creates the file. So I can write to that directory. And the created file is named "test"
package filetest;
import java.io.File;
import java.util.*;
public class FileTest {
public static void main(String[] args) {
File myfile = new File("C:\\test\\test.txt");
final Formatter newfile;
if (myfile.exists()) {
System.out.println("file exists");
} else {
System.out.println("file doesn't exist");
try {
newfile = new Formatter("C://test//test.txt");
System.out.println("file has been created");
} catch(Exception e) {
System.out.println("Error: " + e);
}
}
}
}
In windows path separator used is '\' for these you need to escape backslash.So your code will be something like:
public class FileTest {
public static void main(String[] args) {
File myfile = new File("C:\\test\\test.txt");
if (myfile.exists()) {
System.out.println("file exists");
} else {
System.out.println("file doesn't exist");
}
}
}
You don't need to double your slashes. You have to user wether "/" or "\\".
EDIT :
The weird thing is that I tried it out and both "/" and "\\" work fine for me. In fact, it works regardless of the number of "/" I use... for example "C:////test/////////test.txt" is okay. You have another problem, and I have no idea of what it could be.
I would recommend using isFile() instead of exists(). Its a better way of checking if the path points to a file rather than if a file exists or not. exists() may return true if your path points to a directory.
#SSorensen In your EDITED code, you added the backslash properly
# line 7
File myfile = new File("C:\\test\\test.txt");
but you forgot to update slashes with backslashes # line 14
newfile = new Formatter("C://test//test.txt");

Failed to move file to another directory using renameTo

import java.io.File;
import org.apache.commons.io.FilenameUtils;
public class Tester {
public static void main(String[] args) {
String rootPath = "F:\\Java\\Java_Project";
File fRoot = new File(rootPath);
File[] fsSub = fRoot.listFiles();
for (File file : fsSub) {
if(file.isDirectory()) continue;
String fileNewPath = FilenameUtils.removeExtension(file.getPath()) + "\\" + file.getName();
File fNew = new File(fileNewPath);
try {
file.renameTo(fNew);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
I am trying to move the file to another directory,for instance,if the File path is
"C:\out.txt"
than I want to move to
"C:\out\out.txt"
If i try to print the original File and the new original information, the work well,But they just can not move successful.
I suggest to try Java 7 NIO2
Files.move(Path source, Path target, CopyOption... options)

Check if any Zip file is present on a given path

I want to check whether any Zip file is present on a specified path. If present then I want to extract that file on the same path.
How to check if any Zip file is present on a given path?
You can try this code which checks the extension of the file inside the directory and prints the filename if Zip file is present.
public static void main(String[] args)
{
// Directory path here
String path = ".";
String files;
File folder = new File(path);
File[] listOfFiles = folder.listFiles();
for (int i = 0; i < listOfFiles.length; i++)
{
if (listOfFiles[i].isFile())
{
files = listOfFiles[i].getName();
if (files.endsWith(".rar") || files.endsWith(".zip"))
{
System.out.println(files);
}
}
}
}
Instead of that If you want to use FilenameFilter as told by Andrew Thompson.
You can implement FilenameFilter in your class.
More help is given on this link.
By this you dont need to check the extension of file .
It will give you only those files which extension is being passed as a parameter.
To extract the zip file if found you can take help of the ZipInputStream package .
You can have a look here to extract the folder.
How to check if Any Zip file is present on a given path?
See File.exists()
This unzips all files in a directory, but it's easy to modify to only unzip a specific file.
package com.wedgeless.stackoverflow;
import java.io.*;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
/**
* Unzips all zip files in a directory
* #author mk
*/
public final class Unzipper
{
public static final String DOT_ZIP = ".ZIP";
public static final FilenameFilter DOT_ZIP_FILTER = new FilenameFilter()
{
#Override
public boolean accept(File dir, String name)
{
return name.toUpperCase().endsWith(DOT_ZIP);
}
};
public static void main(String[] args)
{
File dir = new File("/path/to/dir");
Unzipper unzipper = new Unzipper();
unzipper.unzipDir(dir);
}
public void unzipDir(File dir)
{
for (File file : dir.listFiles(DOT_ZIP_FILTER))
{
unzip(file);
}
}
protected void unzip(File file)
{
File dir = getZipDir(file);
try
{
dir.mkdirs();
ZipFile zip = new ZipFile(file);
Enumeration<? extends ZipEntry> zipEntries = zip.entries();
while (zipEntries.hasMoreElements())
{
ZipEntry zipEntry = zipEntries.nextElement();
File outputFile = new File(dir, zipEntry.getName());
outputFile.getParentFile().mkdirs();
if (!zipEntry.isDirectory())
{
write(zip, zipEntry, outputFile);
}
}
}
catch (IOException e)
{
dir.delete();
}
}
protected void write(ZipFile zip, ZipEntry zipEntry, File outputFile)
throws IOException
{
final BufferedInputStream input = new BufferedInputStream(zip.getInputStream(zipEntry));
final int buffsize = 1024;
final byte buffer[] = new byte[buffsize];
final BufferedOutputStream output = new BufferedOutputStream(new FileOutputStream(outputFile), buffsize);
try
{
while (input.available() > 0)
{
input.read(buffer, 0, buffsize);
output.write(buffer, 0, buffsize);
}
}
finally
{
output.flush();
output.close();
input.close();
}
}
protected File getZipDir(File zip)
{
File dir = zip.getParentFile();
int index = zip.getName().toUpperCase().lastIndexOf(DOT_ZIP);
String zipPath = zip.getName().substring(0, index);
File zipDir = new File(dir, zipPath);
return zipDir;
}
}
It's also not puzzled when on those rare occasions you get zip files with a extension in a non-standard case e.g. file.ZIP
edit: I guess I should have read the question more carefully. You only asked how to identify if a zip file existed on a path, not how to extract it. Just use the FilenameFilter approach... if you get any hits return true, otherwise false.
Take a File variable and go through all the files inside the director and ckeck for a .zip or .tar.gz or .rar
How to iterate over the files of a certain directory, in Java?
The best way to test the availability of any resource that you want to use is just to try to use it. Any other technique is vulnerable to timing-window problems, critique that you are trying to predict the future, double coding, etc. etc. etc. Just catch the FileNotFoundException that happens when you try to open it. You have to catch it anyway, why write the same code twice?

Categories

Resources