I have a file copied in one computer and I need to access the file from other computer.
I am not sure, which protocol or which technology to use for this?
Please provide me any hints for this..
Update:
I am using Ubuntu Linux system.
I used the code :
File f = new File("//192.168.1.157/home/renjith/picture.jpg");// 192.168.1.157 is the ip of the computer, where I have the picture file
Image image = ImageIO.read(f);
But it is giving an exception:
javax.imageio.IIOException: Can't read input file!
at javax.imageio.ImageIO.read(ImageIO.java:1275)
I have shared renjith folder also.
There are any number of ways to access files on remote machines, but they virtually all depend on the remote machine having been set up to provide the file in some way first. If you with to access files via java, the easiest method would probably be to set up an HTTP server on the remote machine (this can be done pretty easily using Apache HTTP server on a variety of platforms) and then using Apache Commons HTTPClient on the client side java app. Further discussion of how to install these or configure them is generally beyond the scope of Stack Overflow and would at least require a more specific question
HTTP is an option. However, if these are Windows machines on the same LAN, it would be easier to expose the directory on the remote machine via a file share and access the file through a regular file path. Similarly, if these are Unix-like machines, you could use regular file paths if you're using NFS. FTP's yet another option.
if the remote computer is in the same network and on a shared folder to the computer where your java code is running then try this piece of code for accessing it
File file = new File("\\\\Comp-1\\FileIO\\Stop.txt");
here Comp-1 is the DNS name of the machine containing the file in the network!!!
You might try:
URL url = new URL("file://192.168.1.157/home/renjith/picture.jpg");
Image image = ImageIO.read(url);
You could try to mount that path first, and then load it. Do a :
subst x: \\192.168.1.157
and then:
File f = new File("x:\\home\\renjith\\picture.jpg");
Image image = ImageIO.read(f)
It should work.
Share the directory and access the file thruogh java code
try this one:
File f = new File("//10.22.33.122/images")
File[] files = f.listFiles(new FilenameFilter() {
public boolean accept(File dir, String name) {
// Specify the extentions of files to be included.
return name.endsWith(".bmp") || name.endsWith(".gif");
}
});
// get names of the files
String[] fileNamesArray = null;
for (int indx = 0; indx < files.length(); indx++) {
fileNamesArray[indx] = files[indx].getName();
}
return fileNamesArray;
Map your IP to network drive and try let us say the drive letter is X,
then code changes to File f = new File("x:\\home\\renjith\\picture.jpg");
Infact your file is already loaded in object f , try priting the value of the path f.getAbsolutePath() to console and see.. Actual error is with ImageIO
You can read from remote and write to remote using jcifs-1.3.15.jar jar in java but first you need to share location from remote system then it's possible.
try{
String strLine="";
NtlmPasswordAuthentication auth = new NtlmPasswordAuthentication("WORKGROUP", "username", "passwd"); // Authentication info here, domain can be null
// try (InputStream is = new SmbFile("smb://DESKTOP-0xxxx/usr/local/cache/abc.txt", auth).getInputStream()) {
try (InputStream is = new SmbFile("smb://xx.xx.xx.xxx/dina_share/abc.txt", auth).getInputStream()) {
BufferedReader br = new BufferedReader(new InputStreamReader(is));
while ((strLine = br.readLine()) != null) {
System.out.println(strLine);
}
} catch (IOException e) {
e.printStackTrace();
}
String smbURL="smb://xx.xx.xx.xxx/dina_share/abcOther.txt";
SmbFileOutputStream fos = new SmbFileOutputStream(new SmbFile(smbURL,auth));
byte bytes[]="Wellcome to you".getBytes();
fos.write(bytes);
}catch(Exception e){
e.printStackTrace();
}
Related
I am trying to read file from the Local storage inside the Project of an Android.
However I am still having error like file not found exception. I had print the path of the file and I have checked with the browser file is there on the same path. but I am having still exception.
try {
File file = new File("D:\\Android SDK\\AndroidWorkspace\\Assignment4Test\\app\\src\\main\\assets\\studentnameid.txt");
if (file.exists()) {
System.out.println("File Is there ");
} else {
//It always executes the else blog.
file.createNewFile();
System.out.println(" file is not there so its creating Created File");
}
System.out.println(file.getAbsolutePath());
StringBuilder text = new StringBuilder();
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
while ((line = br.readLine()) != null) {
text.append(line);
text.append('\n');
}
br.close();
} catch (Exception e) {
e.printStackTrace();
}
I would appreciate your help.
Thanks,
Krishna
D:\\Android SDK\\AndroidWorkspace\\Assignment4Test\\app\\src\\main\\assets\\studentnameid.txt is a path to a file on a Windows PC. Android is not Windows. You do not use Windows filesystem paths to refer to anything on Android.
My guess, based on that path, is that you have a file in your project in assets/. If so, use AssetManager (via getAssets() on a Context) and its open() method to access your asset. That will give you an InputStream to read from, directly or via an InputStreamReader.
to simplify this you have to use a localhost WAMP (for Windows ) or MAMP(for Mac), then store your file in the (www) folder, Go to android studio and set the link of your file like ( http://192.168.1.100/studentnameid.txt)
the 192.168.1.100 is your local IP address.
Not: you must change your IP address by the domaine name when you publish your app in Google play or other platforms
I want to access a Hadoop file system through Java remotely, but every time I run the following code it's just showing the Local file system.
I have gone through many solutions on Stack Overflow but nothing seems to work.
Here is a current attempt:
Code
Configuration obj = new Configuration();
obj.set("fs.defaultFS", "hdfs://localhost:8020");
obj.addResource(new Path("/etc/hadoop/conf/core-site.xml"));
obj.addResource(new Path("/etc/hadoop/conf/hdfs-site.xml"));
URI uri = new URI("hdfs://localhost:8020/");
Path path =new Path("/Myfiles/wc.txt");
FileSystem fs = FileSystem.get(obj);
System.out.println(fs.getHomeDirectory());
if(fs instanceof DistributedFileSystem) {
System.out.println("HDFS is the underlying filesystem");
} else {
System.out.println("Other type of file system "+fs.getClass());
}
FSDataInputStream fsDataInputStream = fs.open(path);
InputStreamReader inputStreamReader = new InputStreamReader(fsDataInputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String line;
while((line=bufferedReader.readLine())!=null){
System.out.println(line);
}
bufferedReader .close();
What am I doing incorrectly?
This setting:
obj.set("fs.defaultFS", "hdfs://localhost:8020");
is already present here: ( No sense to use it.)
obj.addResource(new Path("/etc/hadoop/conf/core-site.xml"));
obj.addResource(new Path("/etc/hadoop/conf/hdfs-site.xml"));
These files, of course, are not available outside hadoop cluster. You have to copy them.
If your fs.defaultFS is localhost:8020 this code will work only on the host where the name node is listening, no remotes.
it should be something like
obj.set("fs.default.name", "hdfs://mycluster.local:8020"); ( MRv1 )
obj.set("fs.defaultFS", "hdfs://mycluster.local:8020"); ( YARN )
where my cluster.local resolves to the correct ip address of the name node.
BTW best way to access HDFS from outside is webHDFS.
I am trying to use a jar file which itself is a web application in another web project. In my jar which i have created using eclipse's export to jar functionality, I have stored a directory.To access the files the from that directory i am using
BufferdReader tempDir = new BufferedReader(new InputStreamReader(getClass().getResourceAsStream(myDirPath),"UTF-8"));
// Then i iterate on tempDir
String line;
ArrayList<File> tempDirList = new ArrayList<File>();
int c = 0;
try {
while((line = tempDir.readLine())!= null)
{
File f = new File(line);
tempDirList.add(f);
c++;
}
} catch (IOException e)
{
e.printStackTrace();
}
Now on itrating on tempDirList when i try to read the file i need file path from which i get file but I did not get file path.
So i want to know that how i get file path?
You cannot access the files in the JAR as File objects since in the web container they might not get unpacked (so there is no file). You can only access them via streams as you did.
getClass().getResourceAsStream(myDirPath + "/file1.txt");
If you really need File objects (most of the times it's quite easy to avoid that), copy the files into temporary files which you then can access.
File tmp = File.createTemp("prefix", ".tmp");
tmp.deleteOnExit();
InputStream is = getClass().getResourceAsStream(myDirPath + "/file1.txt");
OutputStream os = new FileOutputStream(tmp);
ByteStreams.copy(is, os);
os.close();
is.close();
But as I said, using streams instead of file objects in the first place makes you more flexible.
If you really don't know all the files in the directory at compile time you might be interested in this answer to list contents.
I can read texts and write them to console however when i install this application to another computer wherever it is installed I dont want to change the path of the txt file. I want to write it like
BufferedReader in = new BufferedReader(new FileReader("xxx.txt"));
I don't want to:
BufferedReader in = new BufferedReader(new FileReader("C:\\Users\\abcde\\Desktop\\xxx.txt"));
is there any way to show this txt file? By the way I put this txt file inside the sources but it cant read!
First get the default application path then check if file exist if exist continue if not close application.
String path = System.getProperty("user.dir");
System.out.println(path + "\\disSoruCevap.txt");
File file = new File(path + "\\disSoruCevap.txt");
if (!file.exists()) {
System.out.println("System couldnt file source file!");
System.out.println("Application will explode");
}
EDIT*
Please prefer one of the answer using resource streams, as you will
see from comments using user.dir is not safe in every case.
You are looking for :
BufferedReader in = new BufferedReader(getClass().getResourceAsStream("/xxx.txt"));
This will load xxx.txt from your jar file (or any jar file in your class path that has that file inside its root directory).
URL fileURL= yourClassName.class.getResource("yourFileName.extension");
String myURL= fileURL.toString();
now you don't need long path name PLUS this one is dynamic in nature i.e., you can now move your project to any pc, any drive.This is because it access URL by using your CLASS location not by any static location (like c:\folder\ab.mp3, then you can't access that file if you move to D drive because then you have to change to D:/folder/ab.mp3 manually which is static in nature)(NOTE: just keep that file with your project)
You can use fileURL as: File file=new File(fileURL.toURI());
You can use myURL as: Media musicFile=new Media(myURL); //in javaFX which need string not url of file
InputStream input = Class_name.class.getResourceAsStream("/xxx.txt");
InputStreamReader inputReader = new InputStreamReader(input);
BufferedReader br = new BufferedReader(inputReader);
String line = null;
try {
while((line = br.readLine())!=null){
System.out.println(line);
}
} catch (IOException ex) {
ex.printStackTrace();
}
You don't need to write or mention long path. Using this code Class_name.class.getResourceAsStream("/xxx.txt"), you can easily get your file.
BufferedReader in = new BufferedReader(new FileReader("xxx.txt")); works fine because when you run your application on an IDE, xxx.txt apparantly is lying in Java's working directory.
Working directory is an operating system feature and it can not be changed.
There are a few ways to deal with this.
1 - use file constructor new File(parent, filename); and load parent using a public static final constant or a property (either passed from command line or otherwise)
2 - or use InputStream in = YourClass.class.getClassLoader().getResourceAsStream("xxx.txt"); - provided your xxx.txt file is packaged under same location as YourClass
Try:
InputStream is = ClassLoader.getSystemResourceAsStream("xxx.txt");
BufferedReader in = new BufferedReader(new InputStreamReader(is));
Depending on where exactly is your file compared to the root of your classpath, you may have to replace xxx.txt3 with /xxx.txt.
My file paths are like this:
public final static String COURSE_FILE_LOCATION = "src/main/resources/courses.csv";
public final static String PREREQUISITE_FILE_LOCATION = "src/main/resources/prerequisites.csv";
This doesn't work. So I delete the .iml file, .idea and target folder from the project and reload them.
Read the correct path like this:
This would work then.
I have a project with 2 packages:
tkorg.idrs.core.searchengines
tkorg.idrs.core.searchengines
In package (2) I have a text file ListStopWords.txt, in package (1) I have a class FileLoadder. Here is code in FileLoader:
File file = new File("properties\\files\\ListStopWords.txt");
But I have this error:
The system cannot find the path specified
Can you give a solution to fix it?
If it's already in the classpath, then just obtain it from the classpath instead of from the disk file system. Don't fiddle with relative paths in java.io.File. They are dependent on the current working directory over which you have totally no control from inside the Java code.
Assuming that ListStopWords.txt is in the same package as your FileLoader class, then do:
URL url = getClass().getResource("ListStopWords.txt");
File file = new File(url.getPath());
Or if all you're ultimately after is actually an InputStream of it:
InputStream input = getClass().getResourceAsStream("ListStopWords.txt");
This is certainly preferred over creating a new File() because the url may not necessarily represent a disk file system path, but it could also represent virtual file system path (which may happen when the JAR is expanded into memory instead of into a temp folder on disk file system) or even a network path which are both not per definition digestable by File constructor.
If the file is -as the package name hints- is actually a fullworthy properties file (containing key=value lines) with just the "wrong" extension, then you could feed the InputStream immediately to the load() method.
Properties properties = new Properties();
properties.load(getClass().getResourceAsStream("ListStopWords.txt"));
Note: when you're trying to access it from inside static context, then use FileLoader.class (or whatever YourClass.class) instead of getClass() in above examples.
The relative path works in Java using the . specifier.
. means same folder as the currently running context.
.. means the parent folder of the currently running context.
So the question is how do you know the path where the Java is currently looking?
Do a small experiment
File directory = new File("./");
System.out.println(directory.getAbsolutePath());
Observe the output, you will come to know the current directory where Java is looking. From there, simply use the ./ specifier to locate your file.
For example if the output is
G:\JAVA8Ws\MyProject\content.
and your file is present in the folder "MyProject" simply use
File resourceFile = new File("../myFile.txt");
Hope this helps.
The following line can be used if we want to specify the relative path of the file.
File file = new File("./properties/files/ListStopWords.txt");
InputStream in = FileLoader.class.getResourceAsStream("<relative path from this class to the file to be read>");
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
String line = null;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
} catch (Exception e) {
e.printStackTrace();
}
try .\properties\files\ListStopWords.txt
I could have commented but I have less rep for that.
Samrat's answer did the job for me. It's better to see the current directory path through the following code.
File directory = new File("./");
System.out.println(directory.getAbsolutePath());
I simply used it to rectify an issue I was facing in my project. Be sure to use ./ to back to the parent directory of the current directory.
./test/conf/appProperties/keystore
While the answer provided by BalusC works for this case, it will break when the file path contains spaces because in a URL, these are being converted to %20 which is not a valid file name. If you construct the File object using a URI rather than a String, whitespaces will be handled correctly:
URL url = getClass().getResource("ListStopWords.txt");
File file = new File(url.toURI());
Assuming you want to read from resources directory in FileSystem class.
String file = "dummy.txt";
var path = Paths.get("src/com/company/fs/resources/", file);
System.out.println(path);
System.out.println(Files.readString(path));
Note: Leading . is not needed.
I wanted to parse 'command.json' inside src/main//js/Simulator.java. For that I copied json file in src folder and gave the absolute path like this :
Object obj = parser.parse(new FileReader("./src/command.json"));
For me actually the problem is the File object's class path is from <project folder path> or ./src, so use File file = new File("./src/xxx.txt"); solved my problem
For me it worked with -
String token = "";
File fileName = new File("filename.txt").getAbsoluteFile();
Scanner inFile = null;
try {
inFile = new Scanner(fileName);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
while( inFile.hasNext() )
{
String temp = inFile.next( );
token = token + temp;
}
inFile.close();
System.out.println("file contents" +token);
If text file is not being read, try using a more closer absolute path (if you wish
you could use complete absolute path,) like this:
FileInputStream fin=new FileInputStream("\\Dash\\src\\RS\\Test.txt");
assume that the absolute path is:
C:\\Folder1\\Folder2\\Dash\\src\\RS\\Test.txt
String basePath = new File("myFile.txt").getAbsolutePath();
this basepath you can use as the correct path of your file
if you want to load property file from resources folder which is available inside src folder, use this
String resourceFile = "resources/db.properties";
InputStream resourceStream = ClassLoader.getSystemClassLoader().getResourceAsStream(resourceFile);
Properties p=new Properties();
p.load(resourceStream);
System.out.println(p.getProperty("db"));
db.properties files contains key and value db=sybase
If you are trying to call getClass() from Static method or static block, the you can do the following way.
You can call getClass() on the Properties object you are loading into.
public static Properties pathProperties = null;
static {
pathProperties = new Properties();
String pathPropertiesFile = "/file.xml";
// Now go for getClass() method
InputStream paths = pathProperties.getClass().getResourceAsStream(pathPropertiesFile);
}