java file.exists doesn't find my file - java

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");

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;
}
}

reading text from a relative file path

I have an absolute file path in my java program that contains some text. This is the code:
import java.io.*;
import java.util.*;
public class RoughCode {
public static void main(String[] args) {
try {
File rules=new File("C:\\Users\\Owner\\Documents\\ICS4U\\Assignment 1\\GameShowRules.txt");
Scanner scan=new Scanner(rules);// scans the file 'rules'
while (scan.hasNextLine()) {
System.out.println(scan.nextLine());// outputs 'rules' to console
}
}
catch(Exception e) {
System.out.println("File not found");
System.exit(0);
}
}
}
Here, the code works just fine. The output I get is whatever is stored in the file, which is:
The rules of the game are:
You must answer 15 multiple-choice questions correctly in a row to win the jackpot.
You may quit at any time and keep the earnings.
However, what I need is a relative file path so that it runs on any laptop.
In an attempt to do that, I did:
import java.io.*;
import java.net.URI;
import java.util.*;
public class RoughCode {
public static void main(String[] args) {
try {
// Two absolute paths
File absolutePath1 = new File("C:\\Users\\Owner\\Documents\\ICS4U\\Assignment 1\\GameShowRules.txt");
File absolutePath2 = new File("C:\\Users\\Owner\\Documents\\ICS4U\\Assignment 1");
// convert the absolute path to URI
URI path1 = absolutePath1.toURI();
URI path2 = absolutePath2.toURI();
// create a relative path from the two paths
URI relativePath = path2.relativize(path1);
// convert the URI to string
String path = relativePath.getPath();
Scanner scan=new Scanner(path);
while (scan.hasNextLine()) {
System.out.println(scan.nextLine());
}
}
catch(Exception e) {
System.out.println("File not found");
System.exit(0);
}
}
}
This does not display the text I need. it just displays "GameshowRules.txt".
How do I get it to output the text stored in the file?
Thanks
Try to use BufferedReader and FileReader. My "data.txt" file is in the same folder as the java program, and works just fine.
I guess you know where will be file of your own program, so you can paste relative path to it.
It looks like this
public class Project {
public static void main(String[] args) throws IOException {
BufferedReader reader = new BufferedReader(new FileReader("data.txt"));
String data;
while ((data = reader.readLine()) != null) {
System.out.println(data);
}
}
}

Java - Can't find and load a CSV file

For some reason, although I have already downloaded the CSV files, my program is unable to read them. My code is below, and it checks if the CSV file exists. If it does not, it goes to the URL and downloads and reads the code. However, it always re-downloads the code although it is in the path folder.
private void loadData(String path, String url) throws IOException{
File f = new File(path);
System.out.println("looking for path " + path);
if(f.exists()) {
readSavedFile(path); //method to load data
}
else{
System.out.println("Need to download from internet");
downloadAndRead(url, path);
}
}
This code outputs
looking for path C:\Users\n_000\workspace\Program\GOOG.csv
Need to download from internet.
looking for path C:\Users\n_000\workspace\Program\CHK.csv
Need to download from internet.
The code that I'm using to create the path is this:
String save = "filename"; //in program use this is the name of the stock eg GOOG or CHK
Path currentRelativePath = Paths.get("");
String savedFolder = currentRelativePath.toAbsolutePath().toString() + "\\";
path = savedFolder+save+".csv";
Its working fine,i didn't see any issues,i am posting my tested code,hope it may be useful.
import java.io.File;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
public class Test {
public static void main(String ar[])
{
Test test=new Test();
}
public Test()
{
String save = "GOOG"; //in program use this is the name of the stock eg GOOG or CHK
Path currentRelativePath = Paths.get("");
String savedFolder = currentRelativePath.toAbsolutePath().toString() + "\\";
String path = savedFolder+save+".csv";
String url=null;
try
{
loadData(path,url);
} catch (IOException e)
{
e.printStackTrace();
}
}
private void loadData(String path, String url) throws IOException
{
File f = new File(path);
System.out.println("looking for path " + path);
if(f.exists()) {
readSavedFile(path); //method to load data
}
else{
System.out.println("Need to download from internet");
downloadAndRead(url, path);
}
}
public void readSavedFile(String path)
{
System.out.println("Reading file");
}
public void downloadAndRead(String url,String path)
{
System.out.println("Downloding file");
}
}

I want to create a class to create a file, and use main class to check if that file is created, but my code fail. (Java)

public class Fileverifynanoha
{
private File fileext;
private Path filepath;
public Fileverifynanoha()//this class wants to create a file, write something, and close it.
{
filepath = Paths.get("./txttest.txt");
Charset charset = Charset.forName("US-ASCII");
String s = "Takamachi Nanoha. Shirasaki Tsugumi.!";
try (BufferedWriter filewriter = Files.newBufferedWriter(filepath,charset))
{
filewriter.write(s,0,s.length()-1);
}
catch(IOException e)
{
System.err.println(e);
}
}//end of this class
/**
* #param args the command line arguments
*/
public static void main(String[] args)//the main method will check if this file contains(created), if so, return exist. if not, return doesnt exist.
{
if (filetxt.exists()&&!filetxt.isDirectory())//object does not create any real thing, therefore nothing true will return.
{
System.out.println("File exist.");
}
else
{
System.out.println("File does not exist.");
}
}
}
Here is the code. I want to use the class I create to create a file, write something. Then, I use main class to check if that file exist.
However, I don't know why, but the main class does not recognise my (maybe) created file. Could anyone tell me how to link them together?
I know there may be some minor bugs in this program. I will fix that later.
Thanks.
You never called your constructor.
public static void main(String[] args)//the main method will check if this file contains(created), if so, return exist. if not, return doesnt exist.
{
Fileverifynanoha fvn = new Fileverifynanoha();
if (fvn.filetxt.exists()&&!fvn.filetxt.isDirectory())
{
System.out.println("File exist.");
}
else
{
System.out.println("File does not exist.");
}
}
}
Your issues:
Didn't create instance of class.
Didn't init File file, so it would be null always.
Better use utf-8 for plain text file.
Try this:
import java.io.BufferedWriter;
import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
public class Fileverifynanoha {
private File file;
private Path path;
public Fileverifynanoha(String fp) {
this.path = Paths.get(fp);
this.file = path.toFile();
}
public void createFile()// this class wants to create a file, write something, and close it.
{
Charset charset = Charset.forName("UTF-8");
String s = "Takamachi Nanoha. Shirasaki Tsugumi.!";
BufferedWriter filewriter = null;
try {
filewriter = Files.newBufferedWriter(path, charset);
filewriter.write(s, 0, s.length() - 1);
filewriter.close();
} catch (IOException e) {
System.err.println(e);
}
}// end of this class
/**
* #param args
* the command line arguments
*/
public static void main(String[] args)// the main method will check if this file contains(created), if so, return exist. if not, return doesnt exist.
{
Fileverifynanoha f = new Fileverifynanoha("./txttest.txt");
f.createFile();
if (f.file.exists() && !f.file.isDirectory())// object does not create any real thing, therefore nothing true will return.
{
System.out.println("File exist.");
} else {
System.out.println("File does not exist.");
}
}
}

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)

Categories

Resources