Reading from one java file and writing to another one - java

I want content of one .java file to the another .java file. I am doing this with FileInput/FileOutput Stream classes in eclipse IDE. I have put one file named FileToFile.java inside Nisarg/src/FiliIO(package).
And I am getting FileNotFoundException at line 12. I want to know why this exception raised?
This is what I actually got at runtime..
Exception in thread "main" java.io.FileNotFoundException: FileToFile.java (The system cannot find the file specified)
at java.io.FileInputStream.open0(Native Method)
at java.io.FileInputStream.open(Unknown Source)
at java.io.FileInputStream.<init>(Unknown Source)
at java.io.FileInputStream.<init>(Unknown Source)
at FileIO.FileToFile.main(FileToFile.java:12)
This is a piece of code:
package FileIO;
import java.io.*;
public class FileToFile {
/**
* #param args
*/
public static void main(String[] args)throws IOException {
// TODO Auto-generated method stub
FileInputStream i=new FileInputStream("FileToFile.java");// Current file content is wanted to be written...
FileOutputStream o=new FileOutputStream("M.java"); // Destination file which is also in same place.(Nisarg/src/FileIO(package)...
int a=0;
while((a=i.read())!=-1)
{
o.write((byte)a);
}
o.close();
i.close();
System.out.print("Done");
}
}
What should be done to achieve my requirements? I have searched but I was unable to where to put the file. Thank you in advance..!!

Java cant find your input file FileToFile.java, that's what is basically mean. You either can specify a absolute file path or find out what folder your main class is located at and place your file FileToFile.java there.
Find the current directory of your main class, use System.getProperty("user.dir")

package fileIO;
import java.io.*;
public class FileToFile {
public static void main(String[] args)throws IOException {
FileInputStream i=new FileInputStream("src\\fileIO\\FileToFile.java");
FileOutputStream o=new FileOutputStream("F:\\M.java");
int a=0;
while((a=i.read())!=-1)
{
o.write((byte)a);
}
o.close();
i.close();
System.out.print("Done");
}
}

You should have to use
1)the absolute path for your file
2)Find the current directory using System.getProperty("user.dir") and place your file there.
3)You can change your current working directory for your application by Go to
run configuration >> Arguments >> Other radio button. Then enter an absolute path name as the working directory for the launched application.Place your file in the specified directory.

Related

Get the path of a file via file explorer

First of all I'm sorry if this question has been asked before or if there is documentation about the topic but i didn't found anything.
I want to make a windows app that open windows file explorer and you can browse for and then select a mp3 file, so you can play it (and replay it) in this program. I know how to open file explorer, this is my code :
import java.awt.Desktop;
import java.io.File;
import java.io.IOException;
public class Main
{
public static void main(String[] args) throws IOException {
Desktop desktop = Desktop.getDesktop();
File dirToOpen = null;
try {
dirToOpen = new File("c:\\");
desktop.open(dirToOpen);
} catch (IllegalArgumentException iae) {
System.out.println("File Not Found");
}
}
}
But i don't know how to select an mp3 file and then get the path of the file, so i can play it later.
I don't think you are approaching this right. You should use something like a FileDialog to choose a file:
FileDialog fd = new FileDialog(new JFrame());
fd.setVisible(true);
File[] f = fd.getFiles();
if(f.length > 0){
System.out.println(fd.getFiles()[0].getAbsolutePath());
}
Since you are only getting 1 MP3 file, you only need the first index of the File array returned from the getFiles() method. Since it is a modal dialog, the rest of your application will wait until after you choose a file. If you want to get multiple files at once, just loop through this aforementioned Files array.
See the documentation here: https://docs.oracle.com/javase/7/docs/api/java/awt/FileDialog.html

Unexpected FileNotFoundException on FileWriter

I am attempting to create a simple text file that I will be writing to.
I receive the following error:
/Library/Java/Home/bin/java -Didea.launcher.port=7542 "-Didea.launcher.bin.path=/Applications/IntelliJ IDEA 14 CE.app/Contents/bin" -Dfile.encoding=UTF-8 -classpath "/Library/Java/Home/lib/deploy.jar:/Library/Java/Home/lib/dt.jar:/Library/Java/Home/lib/javaws.jar:/Library/Java/Home/lib/jce.jar:/Library/Java/Home/lib/jconsole.jar:/Library/Java/Home/lib/management-agent.jar:/Library/Java/Home/lib/plugin.jar:/Library/Java/Home/lib/sa-jdi.jar:/System/Library/Java/JavaVirtualMachines/1.6.0.jdk/Contents/Classes/charsets.jar:/System/Library/Java/JavaVirtualMachines/1.6.0.jdk/Contents/Classes/classes.jar:/System/Library/Java/JavaVirtualMachines/1.6.0.jdk/Contents/Classes/jsse.jar:/System/Library/Java/JavaVirtualMachines/1.6.0.jdk/Contents/Classes/ui.jar:/Library/Java/Home/lib/ext/apple_provider.jar:/Library/Java/Home/lib/ext/dnsns.jar:/Library/Java/Home/lib/ext/localedata.jar:/Library/Java/Home/lib/ext/sunjce_provider.jar:/Library/Java/Home/lib/ext/sunpkcs11.jar:/Users/Adam/IdeaProjects/Data Scraper/out/production/Data Scraper:/Applications/IntelliJ IDEA 14 CE.app/Contents/lib/idea_rt.jar" com.intellij.rt.execution.application.AppMain DataScraper
Exception in thread "main" java.io.FileNotFoundException: ~/Desktop/usernames.txt (No such file or directory)
at java.io.FileOutputStream.openAppend(Native Method)
at java.io.FileOutputStream.<init>(FileOutputStream.java:192)
at java.io.FileWriter.<init>(FileWriter.java:90)
at DataScraper.main(DataScraper.java:16)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:134)
Code:
import Resources.Constants;
import java.awt.*;
import java.io.*;
public class DataScraper {
public static void main(String[] args) throws Exception {
File file = new File(Constants.filePath, Constants.fileName);
Desktop desktop = Desktop.getDesktop();
BufferedWriter Entry = new BufferedWriter(new FileWriter(file, true));
}
}
package Resources;
public class Constants {
public static String baseURL = "www.lolking.net/summoner/na/";
public static String filePath = "~//Desktop//";
public static String fileName = "usernames.txt";
public static int limit = 100;
}
If someone could please guide me through what I'm doing wrong, I would appreciate it. I got this working on my Windows laptop, but on my Mac, it doesn't seem to be working.
public static String filePath = "~//Desktop//";
This will not work. In fact I am surprised that you say that it works on Windows.
You probably meant for the '~' to mean your home directory...
Except that it means this for the shell. Java has no idea what that is. What it will effectively try to do here is find a directory named '~' and an entry named Desktop in it.
Use System.getProperty("user.home") to know what your home diretory it.
And this is 2015, so don't use File. use java.nio.file instead:
final Path path = Paths.get(System.getProperty("user.home"),
"Desktop", "yourFileName");
try (
final BufferedWriter writer = Files.newBufferedWriter(path,
StandardCharsets.UTF_8, StandardOpenOption.APPEND);
) {
// use the writer here
}
You can't use a tilde ~ in your path. If you want the user's home directory, you can get it from System.getProperty("user.home")

How to get the unzipped file directory by using TrueZip

public class unzipAll {
public static void main(final java.lang.String[] args) throws Exception{
TFile src = new TFile("C:/1/BULK.tar.gz");
File dest = new File("C:/Test/");
dest.mkdirs();
try {
src.cp_rp(dest);
TVFS.umount();
} catch (IOException e) {
e.printStackTrace();
}
}
}
I can use this code to unzip BULK.tar.gz. But I want to know the directory of the unzipped files.
Right now, all the files unzipped to C:/Test/. But it has a sub folder "AAAAA".
I want to get this sub folder name "AAAAA" How can I get it?
Try dest.listFiles(). It should give you an array of all files and directories in dest. There are also versions of listFiles that can filter out different kinds of files and/or directories which can be handy at times.
See java api for details: http://docs.oracle.com/javase/7/docs/api/java/io/File.html

Why I'm getting different results using url and absolute file name?

I am new in Java and facing a problem aceessing a file.
I have a package named "FileOperation" uses a "boom.txt" file(Location: "FileOperation/files/boom.txt"). What I wanted to do was to access the file from a class "MyTextPanel" (Location: "FileOperation/MyTextPanel.java").
I have created 2 methods for this purpose. One is by getClass.getResource(path) and other is by giving the absolute location of the file. Second method works, first doesn't. Someone please explain, what's the problem with the first method. Here is the class MyTextPanel:
package FileOperaton;
import java.awt.BorderLayout;
import java.io.FileReader;
import java.net.URL;
import javax.swing.JPanel;
import javax.swing.JTextArea;
public class MyTextPanel extends JPanel {
JTextArea textArea;
MyTextPanel()
{
setLayout(new BorderLayout());
textArea=new JTextArea();
add(textArea,BorderLayout.CENTER);
String fileName;
fileName=getFileName1();
//fileName=getFileName2();
System.out.println("File Name = "+fileName);
if(fileName!=null)
{
try {
FileReader fr=new FileReader(fileName);
System.out.println("Access Successful");
} catch (Exception e) {
e.printStackTrace();
}
}
}
private String getFileName1()
{
URL url=getClass().getResource("/files/boom.txt");
System.out.println("by getFileName1()");
if(url!=null)
return url.getFile();
return null;
}
private String getFileName2()
{
String absolutePath="E:\\Project Eclipse\\Workspace\\FileOperation\\src\\FileOperaton\\files\\boom.txt";
System.out.println("by getFileName2()");
return absolutePath;
}
}
And here are the outputs:
by getFileName1()
File Name =/E:/Project%20Eclipse/Workspace/FileOperation/bin/FileOperaton/files/boom.txt
java.io.FileNotFoundException: E:\Project%20Eclipse\Workspace\FileOperation\bin\FileOperaton\files\boom.txt (The system cannot find the path specified)
at java.io.FileInputStream.open(Native Method)
at java.io.FileInputStream.<init>(Unknown Source)
at java.io.FileInputStream.<init>(Unknown Source)
at java.io.FileReader.<init>(Unknown Source)
at FileOperaton.MyTextPanel.<init>(MyTextPanel.java:32)
at FileOperaton.MyFrame.<init>(MyFrame.java:22)
at FileOperaton.MyFrame.main(MyFrame.java:29)
by second method:
by getFileName2()
File Name = E:\Project Eclipse\Workspace\FileOperation\src\FileOperaton\files\boom.txt
Access Successful
I've also tried url=getClass().getResource("/files/boom.txt") in the first method but there url is assigned as null.
And in the second method, if I use absolutePath="E:\Project Eclipse\Workspace\FileOperation\bin\FileOperaton\files\boom.txt"; (bin instead of src) it also gets success.
Carefully read your output:
First Method:
E:\Project%20Eclipse\Workspace\FileOperation\bin\FileOperaton\files\boom.txt
Second Method:
E:\Project Eclipse\Workspace\FileOperation\src\FileOperaton\files\boom.txt
One time you have the file in the src folder, one time in the bin folder.
I would recommend to make a third folder res and store it there (E:\Project Eclipse\Workspace\FileOperation\res\boom.txt) and the load it like this:
public static URL getFile (String filename)
{
return MyTextPanel.class.getClassLoader().getResource(filename);
}
Here is what I would do if files are in the FileOperation package/folder:
YourClass.class.getResource("/FileOperation/boom.txt");
And here is what you should do when your files are in FileOperation/files folder:
YourClass.class.getResource("/FileOperation/files/boom.txt");
Also, you can look into the bin folder to see whether the boom.txt is there. If not, probably refresh the project using F5 so the files/boom.txt is part of the project.
Well, I have found a solution to my own problem. That could be helpful for others. Doing experiments with the "File Name :" output I figured out that, return of getFile1() and getFile2() actually differs with only a "sapce" charecter.That is "...Project%20Eclipse..."[returned by getFile1()] and "...Project Eclipse..."[returned by getFile2()].So, I have edited the getFile1() method:
private String getFileName1()
{
URL url=getClass().getResource("files/boom.txt");
System.out.println("by getFileName1()");
if(url!=null)
return url.getFile().replaceAll("%20", " ");//<--- replace %20 by space charecter
return null;
}
And Finally it worked. If someone knew, why url generated spaces as %20 and why this wasn't working,that would be better.:)

FileNotFoundException in Eclipse

In Eclipse, my directory structure is this:
-src
-com.xxx.yyy
- MyClass.java
-assets
- car.txt
MyClass.java looks like this :
public class MyClass {
private static String FILE_PATH = "../assets/car.txt";
public static void main(String[] args) {
try {
//FileNotFoundException
FileInputStream fis = new FileInputStream(new File(FILE_PATH));
}
...
}
}
I this by default, the classpath is src/, so I point to my car.txt file by ../assets/car.txt. But I get :
java.io.FileNotFoundException: ../assets/car.txt (No such file or directory)
at java.io.FileInputStream.open(Native Method)
at java.io.FileInputStream.<init>(FileInputStream.java:138)
Why ?
Relative file paths a relative to the execution, assuming that the program is executed in the same location as the src and assets directory, then the path should be assets/car.txt
You can check the current execution location using System.out.println(new File(".").getCanonicalPath());
Whe you run the program it is compiled to the parent folder of the src folder as far as I know. You should better add the assets folder to your build path and access the file using getClass().getResource[AsStream]().
To add the folder do the following:
Right click on your project
Click Build Path
Choose Configure Build Path
Select Source
Click Add Folder...
Select your assets folder
Inside your code you can either call it with MyClass.class.getResource[AsStream]() or getClass().getResource[AsStream]().
getResource() returns an URL and getResourceAsStream() an InputStream. Both methods expect a path as parameter. Check the docs for more information.
Your path is incorrect
Since you are inside com.xxx.yyy, you are inside three folders. You need to get out of all of them.
So you can use, the relative path as
FILE_PATH = "../../../assets/car.txt";
As src is a source folder, all the contents come directly in the classpasth, you can also use
FILE_PATH = "assets/car.txt";
You are in second level in directory structure.
Try
FILE_PATH = "../../assets/car.txt";
Hope, this will help you...
package com.xxx.yyy;
import java.io.File;
import java.io.FileInputStream;
public class MyClass {
private static String FILE_PATH = "src/assets/car.txt";
public static void main(String[] args) {
try {
//FileNotFoundException
FileInputStream fis = new FileInputStream(new File(FILE_PATH));
}
catch (Exception e){
e.printStackTrace();
}
}
}
Ankit Lamba 's suggestion works: that's using String FILE_PATH = "assets/car.txt";

Categories