How to use file not full path - java

Although file(deneme.txt) is in the same src file with runner class. Why cannot I use just file name?
import java.io.File;
public class Runner {
public static void main(String []args) {
//File file = new File("deneme.txt");
File file = new File("C:\\Users\\serha\\eclipse-workspace\\HW1\\src\\deneme.txt");
System.out.println(file.exists());
System.out.println(file.isFile());
}
}

Related

FileReader in Java not finding the file

I'm trying to read a plain text file but somehow FileReader is not finding my text file. I checked the directory using getAbsolutefile() and /Users/djhanz/IdeaProjects/datalab2/pg174.txt is the exact location of the file. I tried datlab2/pg174.txt and everything I possibly could.
Here is my code
public class Program1 {
public static void main(String[] args) {
System.out.println(new File("pg174.txt").getAbsoluteFile());
Scanner testScanner = new Scanner(new BufferedReader(new FileReader("/Users/djhanz/IdeaProjects/datalab2/pg174.txt")));
while (testScanner.hasNextLine())
{
System.out.println(testScanner.nextLine());
}
}
}
The text file is under the same project directory called datalab.
Can someone please enlighten me?
Use Scanner testScanner = new Scanner(new BufferedReader(new FileReader("/pg174.txt")));
FileReader("/pg174.txt") instead of FileReader("pg174.txt").
package com.example.demo;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.util.Scanner;
public class Program1 {
public static void main(String[] args) throws FileNotFoundException {
System.out.println(new File("pg174.txt").getPath());
System.out.println(new File("pg174.txt").getAbsoluteFile());
System.out.println(new File("pg174.txt").getAbsolutePath());
Scanner testScanner = new Scanner(new BufferedReader(new FileReader("/pg174.txt")));
while (testScanner.hasNextLine()) {
System.out.println(testScanner.nextLine());
}
}
}
Output:

Prevent deleting lock file using nio

We want to prevent other processes from deleting the temp directory of our running application. That way we create a temp directory and a lock file in it. The only way I found at that prevents deleting this file is by using RandomAccessFile:
tempDirectory = Files.createTempDirectory("myapp");
final Path lockFile = Files.createTempFile(tempDirectory, "lock", null);
randomAccessFile = new RandomAccessFile(lockFile.toFile(), "rw");
Is there a way to achieve the same with nio? I have tried with the following code:
import java.io.*;
import java.nio.channels.*;
import java.nio.file.*;
public class CreateLock {
public static void main(String[] args) throws IOException, InterruptedException {
final Path path = Paths.get("C:/temp/test");
Files.createFile(path);
final FileChannel channel = FileChannel.open(path, StandardOpenOption.WRITE);
channel.lock();
for (int i = 60; i-- > 0; ) {
System.out.println(i);
if (!Files.isRegularFile(path)) {
System.out.println("File is gone");
break;
}
Thread.sleep(10_000);
}
channel.close();
}
}
but a second Java application with this code
import java.io.*;
import java.nio.file.*;
public class DeleteLock {
public static void main(String[] args) throws IOException {
final Path path = Paths.get("C:/temp/test");
Files.delete(path);
}
}
can delete the file.
Please try below:
FileChannel ch = FileChannel.open(lockFile.toAbsolutePath(), StandardOpenOption.WRITE);
ch.lock();

How can I read a file from a path relative of my Main class in Java?

On the same directory of my Main.java file, I have a package/folder named database, and inside the database package I have a file named Data.txt.
This is my code of Main.java, but it is throwing this error:
java: exception java.io.FileNotFoundException
How can I get the file from a relative file? I'm used to web development, and usually something with a . dot like "./folder/file.txt" works.
import java.io.File;
import java.util.Scanner;
import java.io.FileNotFoundException;
public class Main {
public static void main(String[] args) {
readFile();
}
public static void readFile() {
File file = new File("./database/Data.txt");
Scanner scanner = new Scanner(file);
try {
while (scanner.hasNextLine()) {
int i = scanner.nextInt();
System.out.println(i);
}
scanner.close();
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
You are not importing FileNotFoundException class. also, scanner statement throws the exception which should inside try. Solution is as below.
import java.io.File;
import java.util.Scanner;
import java.io.FileNotFoundException;
public class Main {
public static void main(String[] args) {
readFile();
}
public static void readFile() {
File file = new File("database/Data.txt");
try {
Scanner scanner = new Scanner(file);
while (scanner.hasNextLine()) {
int i = scanner.nextInt();
System.out.println(i);
}
scanner.close();
}catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
Only check if those content can read using scanner or not. Content having int properly. otherwise it will throw java.util.InputMismatchException.
Are you working on a mac or windows system.
I am on windows and ".\database\Data.txt" would most probably work depending on where the file is in your file structure.

How to use relative filepath in java

Im trying to use relative path to read a file but the path cant be found.
maxSuccession is the name of my project
This is my workspace path: C:\Programming
This is my project's path C:\Programming\MaxSuccessions\maxSuccessions
This is my filepath C:\Programming\MaxSuccessions\Tests\test1\00.in.txt
package test1;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Scanner;
public class test1 {
public static void main(String[] args) throws IOException {
String myPath="..\\MaxSuccessions\\Tests\\test1\\";
Scanner sc = new Scanner(new File(myPath+"00.in.txt"));
System.out.println(sc.nextInt());
}
}
If your class file and required file are in the same directory, you can try this code:
public static void main(String[] args) {
String fileName = "00.in.txt"; //relative path from the path of your class.
try {
Scanner sc = new Scanner(Test.class.getResource(fileName).openStream());
System.out.println(sc.nextInt());
} catch (IOException e) {
e.printStackTrace();
}
}

Trying to copy files in specified path with specified extension and replace them with new extension

I have most of it down but when I try to make the copy, no copy is made.
It finds the files in the specified directory like it is supposed to do and I think the copy function executes but there aren't any more files in the specified directory. Any help is appreciated. I made a printf function that isn't shown here. Thanks!
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.Scanner;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.FileUtils;
import static java.nio.file.StandardCopyOption.*;
public class Stuff {
static String path, oldExtn, newExtn;
static Boolean delOrig = false;
private static void getPathStuff() {
printf("Please enter the desired path\n");
Scanner in = new Scanner(System.in);
path = in.next();
printf("Now enter the file extension to replace\n");
oldExtn = in.next();
printf("Now enter the file extension to replace with\n");
newExtn = in.next();
in.close();
}
public static void main(String[] args) {
getPathStuff();
File folder = new File(path);
printf("folder = %s\n", folder.getPath());
for (final File fileEntry : folder.listFiles()) {
if (fileEntry.getName().endsWith(oldExtn)) {
printf(fileEntry.getName() + "\n");
File newFile = new File(FilenameUtils.getBaseName(fileEntry
.getName() + newExtn));
try {
printf("fileEntry = %s\n", fileEntry.toPath().toString());
Files.copy(fileEntry.toPath(), newFile.toPath(),
REPLACE_EXISTING);
} catch (IOException e) {
System.err.printf("Exception");
}
}
}
}
}`
The problem is that the new file is created without a full path (only the file name). So your new file is created - only not where you expect...
You can see that it'll work if you'll replace:
File newFile = new File(FilenameUtils.getBaseName(fileEntry
.getName() + newExtn));
with:
File newFile = new File(fileEntry.getAbsolutePath()
.substring(0,
fileEntry.getAbsolutePath()
.lastIndexOf(".")+1) + newExtn);

Categories