not sure why this won't read my txt file saved in the same directory. it compiled just fine but then when i enter java BlindfoldsAside into the cmd ln, it says it cannot find or load my main class BlindfoldsAside. The case is all correct as far as I can see and everything is in the right file path, so I'm not sure where i went wrong!
package blindfoldsaside;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.IOException;
import java.util.Scanner;
public class BlindfoldsAside {
public static void main (String[] args) {
Scanner scannerIn = null;
FileInputStream in = null;
BufferedReader inputStream = null;
int fileChar; //character's int equivalent
String fileLine;
try {
// FileInputStream calls the txt file
in = new FileInputStream("blindfoldsaside.txt");
System.out.println("These lyrics tell the story of a woman, named Kezia, who is" +
" \nbeing put to death after being forced into prostitution. This song is from the prison" +
" \nguard's (who is also the executioner) point of view. I hope you enjoy.");
// this reads the file one char at a time
while ((fileChar = in.read()) != -1) {
System.out.print((char) fileChar);
}// end while
System.out.println(""); //separates the file output
System.out.println("");
System.out.println("This song was written by Arif Mirabdolbaghi (bassist) and performed by " +
" Protest the Hero. This song appears on the band's first full length album, Kezia, " +
" released in their native country (Canada) on August 30th, 2005 and to the U.S. on " +
" April 4th, 2006. This is the 6th track on the album.");
} catch (IOException io) {
System.out.println("File IO exception" + io.getMessage());
} finally {
try {
if (in != null) {
in.close();
}// end if
if (inputStream != null) {
inputStream.close();
}// end if
} catch (IOException io) {
System.out.println("There was a problem closing your files" + io.getMessage());
}// end catch
}// end finally
}// end main
}// end class
Try moving the txt file into the project root folder. that should work with no issues. Lest me know if something changed or if it worked fine.
Related
i need an approach with Java to make the Programm know when a File in Linux has been modified. I have tried Files.getLastModifiedTime(), BasicFileAttributes and lastModified. Unfortunately this has not work.
The Scenarios
Scenario A:
an empty Textfile beeing copied from A to B Folder.
then the same empty Textfile in A beeing edited and written something like "Hello World!!!" in an Editor and then copy this file again in Folder B.
Scenario B:
an empty Textfile beeing copied from A to B Folder.
then the same empty Textfile beeing copied again in Folder B.
*In Scenario A my Java Programm identify a modified File in Folder B. I use a timestamp in (dd.MM.yyyy HH:mm:SS) to give it some Unique Identifikation when i relate this Timestamp with its filename as Strings.
*But in Scenario B my Java Programm identify this file also als modified, even though there hasnt been any changes to this Textfile, its the same and its empty in Folder B. I dont know which attribute to use in Java in order to make the programm know that this File has not been modified.(This only happened to me in Linux)
I use openSuse Leap for the Linux environment and Java openJdk 1.8 for my Programm.
As this Programm starts ill copy the 2 existing files in "/tmp/testfolder" to
"/tmp/testfolder/AFolder" with a Linux cp command.
It seems to me that openSUSE Leap doesnt save the Last modified data on its files,
because i get a new and same timestamp for values in Folder A and Folder B.
This doesnt happen in Linux Mint. Unfortunately my company uses openSuse Leap :(
My code:
package com.company;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.LinkOption;
import org.apache.commons.io.FileUtils;
public class App
{
public static void main( String[] args )
{
File textFile1 = new File("/tmp/testfolder/TextFile1.txt");
File textFile2 = new File("/tmp/testfolder/TextFile2.txt");
File textFile1CopyInA = new File("/tmp/testfolder/AFolder/TextFile1.txt");
File textFile2CopyInA = new File("/tmp/testfolder/AFolder/TextFile2.txt");
File textFile1CopyInB = new File("/tmp/testfolder/BFolder/TextFile1.txt");
File textFile2CopyInB = new File("/tmp/testfolder/BFolder/TextFile2.txt");
File bfolder = new File("/tmp/testfolder/BFolder/");
try {
System.out.println("Last Modified of File at testFolder" + textFile1.getAbsolutePath() + " :: " + Files.getLastModifiedTime(textFile1.toPath(), LinkOption.NOFOLLOW_LINKS));
System.out.println("Last Modified of File at testFolder" + textFile2.getAbsolutePath() + " :: " + Files.getLastModifiedTime(textFile2.toPath(), LinkOption.NOFOLLOW_LINKS));
BufferedWriter writer = new BufferedWriter(new FileWriter(textFile1));
String data = "Hello World!!!";
writer.write(data);
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
while(true) {
if((textFile1CopyInA.exists())&&(textFile2CopyInA.exists())){
try {
System.out.println("Last Modified of File in A" + textFile1CopyInA.getAbsolutePath() + " :: " + Files.getLastModifiedTime(textFile1CopyInA.toPath(), LinkOption.NOFOLLOW_LINKS));
System.out.println("Last Modified of File in A" + textFile2CopyInA.getAbsolutePath() + " :: " + Files.getLastModifiedTime(textFile2CopyInA.toPath(), LinkOption.NOFOLLOW_LINKS));
FileUtils.copyFileToDirectory(textFile1CopyInA, bfolder);
FileUtils.copyFileToDirectory(textFile2CopyInA, bfolder);
} catch (IOException e) {
e.printStackTrace();
}
}
if((textFile1CopyInB.exists())&&(textFile2CopyInB.exists())){
try {
System.out.println("Last Modified of File in B " + textFile1CopyInB.getAbsolutePath() + " :: " + Files.getLastModifiedTime(textFile1CopyInB.toPath(), LinkOption.NOFOLLOW_LINKS));
System.out.println("Last Modified of File in B" + textFile2CopyInB.getAbsolutePath() + " :: " + Files.getLastModifiedTime(textFile2CopyInB.toPath(), LinkOption.NOFOLLOW_LINKS));
} catch (IOException e) {
e.printStackTrace();
}
}
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
Thanks a lot in Advance!!
I want to check if a folder exist in the datalake. If exist create a file in it and If folder doesn't exist create folder and then create a file inside the folder
File directory = new File("/Raw/TEST_1/test");
System.out.println("check if directory exist");
if (directory.exists() == false) {
client.createDirectory("/Raw/TEST_1/test");
System.out.println("Directory created.");
OutputStream stream = client.createFile("/Raw/TEST_1/test/" + FuFileName, IfExists.OVERWRITE);
} else {
System.out.println("Directory exist.");
OutputStream stream = client.createFile("/Raw/TEST_1/test" + FuFileName, IfExists.OVERWRITE);
}
} catch (ADLException ex) {
printExceptionDetails(ex);
} catch (Exception ex) {
System.out.format(" Exception: %s%n Message: %s%n", ex.getClass().getName(), ex.getMessage());
}
every time directory.exists() gives me output false even if that folder exist if not giving directory.exists()output as true and not executing else statements
If you are using Java 7 or higher, then it is recommended to use java.nio in order to access the file system.
This very simple example can tell you if a given path is existing and if it is a directory or something else:
import java.nio.file.Path;
import java.nio.file.Paths;
...
public static void main(String[] args) {
Path dirPath = Paths.get("/Raw/TEST_1/test");
if (Files.exists(dirPath)) {
System.out.println(dirPath.toAbsolutePath().toString()
+ " exists on the file system");
if (Files.isDirectory(dirPath)) {
System.out.println(dirPath.toAbsolutePath().toString()
+ " is a directory");
} else {
System.err.println(dirPath.toAbsolutePath().toString()
+ " is not a directory");
}
} else {
System.err.println(dirPath.toAbsolutePath().toString()
+ " does not exist on the file system");
}
}
I want to delete a .dat file. This is my code but it does not work.
String searchCust = SearchCust.getText();
File file = new File(searchCust + " booking.dat");
if (file.delete()) {
JOptionPane.showMessageDialog(null, "Info deleted");
} else {
JOptionPane.showMessageDialog(null, "Delete failed");
}
Basically when i run, the file is not deleted and the "Delete failed" message will appear
File.delete() will return true only if it deletes the file. Meaning it will return false if the file does not exist. Ensure File.exists() returns true prior to invoking File.delete():
if (file.exists())
{
if (file.delete())
{
}
else
{
}
}
Also see Files.deleteIfExists() which may provide more information, via an IOException, in the event of a failed deletion attempt:
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
try
{
final Path p = Paths.get(searchCust + " booking.dat");
if (Files.deleteIfExists(p))
{
JOptionPane.showMessageDialog(null, "Deleted " + p);
}
else
{
JOptionPane.showMessageDialog(null, p + " does not exist.");
}
}
catch (final IOException e)
{
JOptionPane.showMessageDialog(null, e.getMessage());
}
if(file.exists()){
boolean isDelete = file.delete();
if(isDelete){
//condition
}else{
//condition
}
}
Code looks good
fileObject.delete() is the way to delete the record. But you should know what is the current working directory in java first.
Try the below command. Check for its availability : fileObject.exists()
System.getProperty("user.dir"); // fetches the current working directory.
This is the approach, you can fix this problem.
I've basically copied the below code from a text book. I've had this kind of error before and managed to fix it but because I'm not familiar with the Classes & Methods used I am having a bit a trouble with this one.
Below is the error thrown by the compiler.
TextReader.java:27: error: cannot find symbol output = new BufferedOutputStream(filePath.newOutputStream());
symbol: method newOutputStream()
location: variable filePath of type Path
Below is the code. It is basically supposed to get input from a user write it to a text file then read the text file and display the info to the user.
import java.nio.file.*;
import static java.nio.file.StandardOpenOption.*;
import java.io.*;
import javax.swing.JOptionPane;
public class TextReader
{
public static void main (String[]args)
{
Path filePath = Paths.get("Message.txt");
String s = JOptionPane.showInputDialog(null,"Enter text to save as a file","Text File Creator",JOptionPane.INFORMATION_MESSAGE);
byte[] data = s.getBytes();
OutputStream output = null;
InputStream input = null;
try
{
output = new BufferedOutputStream(filePath.newOutputStream());
output.write(data);
output.flush();
output.close();
}
catch(Exception e)
{
JOptionPane.showMessageDialog(null,"Message: " + e,"Error!!",JOptionPane.WARNING_MESSAGE);
}
try
{
input = filePath.newInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(input));
String ss = null;
ss = reader.readLine();
JOptionPane.showMessageDialog(null,"Below is the information from the saved file:\n" + ss,"Reader Output",JOptionPane.INFORMATION_MESSAGE);
input.close();
}
catch (IOException ee)
{
JOptionPane.showMessageDialog(null,"Message: " + ee,"Error!!",JOptionPane.WARNING_MESSAGE);
}
}
}
Path doesn't have a method newOutputStream(). I usually use new FileOutputStream(File) for writing to files, though there might be newer API in Java 7.
You should really use an IDE, e.g. Ecplise or Netbeans, as it will instantly tell you that the method doesn't exist, and will make writing code a thousand times easier in general. For example you can press ctrl+space in Eclipse and it will bring up a list of classes/methods/variables that match the last word you typed (the list will also automatically pop up when typing a period).
Well, my code is as below. I'd like to know why there's always an exception. The mp3 file is in the same directory as the test.java file. What am I doing wrong? Also, how do I read mp3 files from say my Music Library : path - Libraries\Music
import java.io.IOException;
import com.mpatric.mp3agic.ID3v1;
import com.mpatric.mp3agic.InvalidDataException;
import com.mpatric.mp3agic.Mp3File;
import com.mpatric.mp3agic.UnsupportedTagException;
public class test
{
public static void main(String args[])
{
Mp3File mp3file = null;
try {
mp3file = new Mp3File("dom.mp3");
} catch (UnsupportedTagException | InvalidDataException | IOException e) {
// TODO Auto-generated catch block
//e.printStackTrace();
System.out.println("File not found.");
}
if (mp3file.hasId3v1Tag()) {
ID3v1 id3v1Tag = mp3file.getId3v1Tag();
System.out.println("Track: " + id3v1Tag.getTrack());
System.out.println("Artist: " + id3v1Tag.getArtist());
System.out.println("Title: " + id3v1Tag.getTitle());
System.out.println("Album: " + id3v1Tag.getAlbum());
System.out.println("Year: " + id3v1Tag.getYear());
System.out.println("Genre: " + id3v1Tag.getGenre() + " (" + id3v1Tag.getGenreDescription() + ")");
System.out.println("Comment: " + id3v1Tag.getComment());
}
}
}
Exception
java.io.FileNotFoundException: File not found dom.mp3
at com.mpatric.mp3agic.FileWrapper.init(FileWrapper.java:26)
at com.mpatric.mp3agic.FileWrapper.<init>(FileWrapper.java:19)
at com.mpatric.mp3agic.Mp3File.<init>(Mp3File.java:53)
at com.mpatric.mp3agic.Mp3File.<init>(Mp3File.java:41)
at test.main(test.java:13)
File not found.
Exception in thread "main" java.lang.NullPointerException at test.main(test.java:19)
The mpatric package is 3rd party. I'm guessing that works fine.
What do you mean by "same directory as you run your java process from"? Can you give me a for instance, please?
Printing this:
System.out.println("File not found.");
is misleading, given this:
catch (UnsupportedTagException | InvalidDataException | IOException e)
You need to dump the exception (e.printStackTrace() to determine the real issue).
Your .mp3 file is in the same directory as your .java file. But that's not relevant. Is it in the same directory as where you run your java process from ? That's where it needs to be.
e.g.
$ cd /mydir
$ java com.whatever.TestJava
In the above your .mp3 file needs to be in the /mydir directory
As mentioned by #BrianAgnew, you should dump your Exception.
UPDATE
Try this and select your file you want to use:
public class Test
{
public static void main(String args[])
{
Mp3File mp3file = null;
try {
JFileChooser jfc = new JFileChooser();
int fileResult = jfc.showOpenDialog(null);
if (fileResult == JFileChooser.APPROVE_OPTION) {
String path = jfc.getSelectedFile().getPath();
mp3file = new Mp3File(path);
if (mp3file!=null && mp3file.hasId3v1Tag()) {
ID3v1 id3v1Tag = mp3file.getId3v1Tag();
System.out.println("Track: " + id3v1Tag.getTrack());
System.out.println("Artist: " + id3v1Tag.getArtist());
System.out.println("Title: " + id3v1Tag.getTitle());
System.out.println("Album: " + id3v1Tag.getAlbum());
System.out.println("Year: " + id3v1Tag.getYear());
System.out.println("Genre: " + id3v1Tag.getGenre() + "("+id3v1Tag.getGenreDescription() + ")");
System.out.println("Comment: " + id3v1Tag.getComment());
} else {
System.out.println("The mp3 file does not exists or does not have a ID3v1Tag");
}
}
} catch (UnsupportedTagException | InvalidDataException | IOException e) {
System.err.println("File not found.");
e.printStackTrace();
}
}
}
Solved it! System.out.println(System.getProperty("user.dir")); Pasted that into my code, found out the root dir. Apparently it's on the same level as the src and bin folders. Pasted the file there and it works like a charm now.
Alright, if anyone was wondering if you can change the home directory, you can't.
If you want to access another folder, you'll have to resort to directory traversal. Say your music file "Ride the Lightning.mp3" is in C:\Users\"Your Username"\Music\
Then to read that you'll have to do something like this:
mp3file = new Mp3File("../../../Music/Misc/Ride the Lightning.mp3");
Cheers to Brian and Chasmo for the helpful posts.