Printing contents of an imported class to console in java - 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;
}
}

Related

java file.exists doesn't find my file

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

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)

How to unzip a zip folder containing different file formats using Java

I need to unzip a zipped directory containing different files' format like .txt, .xml, .xls etc.
I am able to unzip if the directory contains only .txt files but it fails with other files format. Below is the program that I am using and after a bit of googling, all I saw was similar approach -
import java.io.*;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
public class ZipUtils {
public static void extractFile(InputStream inStream, OutputStream outStream) throws IOException {
byte[] buf = new byte[1024];
int l;
while ((l = inStream.read(buf)) >= 0) {
outStream.write(buf, 0, l);
}
inStream.close();
outStream.close();
}
public static void main(String[] args) {
Enumeration enumEntries;
ZipFile zip;
try {
zip = new ZipFile("myzip.zip");
enumEntries = zip.entries();
while (enumEntries.hasMoreElements()) {
ZipEntry zipentry = (ZipEntry) enumEntries.nextElement();
if (zipentry.isDirectory()) {
System.out.println("Name of Extract directory : " + zipentry.getName());
(new File(zipentry.getName())).mkdir();
continue;
}
System.out.println("Name of Extract fille : " + zipentry.getName());
extractFile(zip.getInputStream(zipentry), new FileOutputStream(zipentry.getName()));
}
zip.close();
} catch (IOException ioe) {
System.out.println("There is an IoException Occured :" + ioe);
ioe.printStackTrace();
}
}
}
Throws the below exception -
There is an IoException Occured :java.io.FileNotFoundException: myzip\abc.xml (The system cannot find the path specified)
java.io.FileNotFoundException: myzip\abc.xml (The system cannot find the path specified)
at java.io.FileOutputStream.open(Native Method)
at java.io.FileOutputStream.<init>(FileOutputStream.java:212)
at java.io.FileOutputStream.<init>(FileOutputStream.java:104)
at updaterunresults.ZipUtils.main(ZipUtils.java:43)
When you try to open the file that is going to contain the extracted content, the error occurs.
This is because the myzip folder is not available.
So check if it indeed is not available and create it before extracting the zip:
File outputDirectory = new File("myzip");
if(!outputDirectory.exists()){
outputDirectory.mkdir();
}
As #Perception pointed out in the comments: The output location is relative to the active/working directory. This is probably not very convenient, so you might want to add the extraction location to the location of the extracted files:
File outputLocation = new File(outputDirectory, zipentry.getName());
extractFile(zip.getInputStream(zipentry), new FileOutputStream(outputLocation));
(of course you need also add outputLocation to the directory creation code)
This is a good example in which he showed to unzip all the formats (pdf, txt etc) have look its quite
or you can use this code might work (i haven't tried this)
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
public class ZipUtils
{
private static final int BUFFER_SIZE = 4096;
private static void extractFile(ZipInputStream in, File outdir, String name) throws IOException
{
byte[] buffer = new byte[BUFFER_SIZE];
BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(new File(outdir,name)));
int count = -1;
while ((count = in.read(buffer)) != -1)
out.write(buffer, 0, count);
out.close();
}
private static void mkdirs(File outdir,String path)
{
File d = new File(outdir, path);
if( !d.exists() )
d.mkdirs();
}
private static String dirpart(String name)
{
int s = name.lastIndexOf( File.separatorChar );
return s == -1 ? null : name.substring( 0, s );
}
/***
* Extract zipfile to outdir with complete directory structure
* #param zipfile Input .zip file
* #param outdir Output directory
*/
public static void extract(File zipfile, File outdir)
{
try
{
ZipInputStream zin = new ZipInputStream(new FileInputStream(zipfile));
ZipEntry entry;
String name, dir;
while ((entry = zin.getNextEntry()) != null)
{
name = entry.getName();
if( entry.isDirectory() )
{
mkdirs(outdir,name);
continue;
}
/* this part is necessary because file entry can come before
* directory entry where is file located
* i.e.:
* /foo/foo.txt
* /foo/
*/
dir = dirpart(name);
if( dir != null )
mkdirs(outdir,dir);
extractFile(zin, outdir, name);
}
zin.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
Regards

Reading from a text file throws exception

So I've used DataInputStream, FileInputStream, BufferInputStream, FileReader, BufferedReader, Scanner, you name it. They all throw FileNOtFoundException or CorruptedStreamException.
the exception
java.io.FileNotFoundException: java.io.FileReader#253498.data (The system cannot find the file specified)
gets thrown on the line where the FileReader is initialized with the filename "Accounts.txt", which is a file that i HAVE initialized, in the bin, with the text needed in it.
import java.io.*;
import java.util.ArrayList;
/**
* Class to load account files
*/
public class AccountLoader {
/**
* Add an account file
* #param newAccount
*/
public static void addAcountFile(Account newAccount) {
try {
PrintWriter out = new PrintWriter(new File("Accounts.txt"));
out.print(" " + newAccount.getOwner().getName());
System.out.println("saved account " + newAccount.getOwner().getName());
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
public static ArrayList<Account> loadAccountsList() throws EOFException, IOException, ClassNotFoundException{
ArrayList<Account> accounts = new ArrayList();
FileReader load = new FileReader("Accounts.txt");
String file = load.toString();
String[] accountsload = file.split(" ");
for (String string : accountsload){
accounts.add(loadAccount(string + ".data"));
}
load.close();
return accounts;
}
public static void save(Account account) {
String filename = account.getOwner().getName() + ".data" ;
if (filename != null) {
try {
FileOutputStream fos = new FileOutputStream(filename);
ObjectOutputStream out = new ObjectOutputStream(fos);
out.writeObject(account);
out.flush();
out.close();
}
catch (IOException e) { System.out.println(e); }
}
}
public static Account loadAccount(String filename) {
Account newAccount = null;
if (filename != null) {
try {
FileInputStream fis = new FileInputStream(filename);
ObjectInputStream in = new ObjectInputStream(fis);
newAccount = (Account)in.readObject();
in.close();
}
catch (Exception e) { System.out.println(e); }
}
return newAccount;
}
}
You probably need to put the text file in the "project root" folder (the one that contains src and bin), not the bin folder. If you're running this from Eclipse that's definitely what you need to do, since the context for Java projects run from Eclipse is always the Eclipse project folder for that project.
When you ask Java to open a file by name without giving it a path, the JVM will look for the file in its current working directory. The current working directory changes depending on how you run the program, and in your case it looks like the "bin" folder is not your current working directory.
Try moving the text file to some other folders. One folder out of the bin folder is probably the right location.
If you are using command line, put the file in the folder from where you are running the java command and add . in the CLASSPATH as
set CLASSPATH=%CLASSPATH%;.
and then run your java program.
If you are using eclipse, try putting the file in root folder of the project or use the relative path with respect to root folder.

how to read directories in java

simple: how do i read the contents of a directory in Java, and save that data in an array or variable of some sort? secondly, how do i open an external file in Java?
You can use java IO API. Specifically java.io.File, java.io.BufferedReader, java.io.BufferedWriter etc.
Assuming by opening you mean opening file for reading. Also for good understanding of Java I/O functionalities check out this link: http://download.oracle.com/javase/tutorial/essential/io/
Check the below code.
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
public class FileIO
{
public static void main(String[] args)
{
File file = new File("c:/temp/");
// Reading directory contents
File[] files = file.listFiles();
for (int i = 0; i < files.length; i++) {
System.out.println(files[i]);
}
// Reading conetent
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader("c:/temp/test.txt"));
String line = null;
while(true)
{
line = reader.readLine();
if(line == null)
break;
System.out.println(line);
}
}catch(Exception e) {
e.printStackTrace();
}finally {
if(reader != null)
{
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
You can use a class java.io.File to do that. A File is an abstract representation of file and directory pathnames. You can retrieve the list of files/directories within it using the File.list() method.
There's also the Commons IO package which has a variety of methods for manipulating files and directories.
import java.io.File;
import java.io.IOException;
import java.util.Collection;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.filefilter.FileFilterUtils;
public class CommonsIO
{
public static void main( String[] args )
{
// Read the contents of a file into a String
try {
String contents = FileUtils.readFileToString( new File( "/etc/mtab" ) );
} catch (IOException e) {
e.printStackTrace();
}
// Get a Collection of files in a directory without looking in subdirectories
Collection<File> files = FileUtils.listFiles( new File( "/home/ross/tmp" ), FileFilterUtils.trueFileFilter(), null );
for ( File f : files ) {
System.out.println( f.getName() );
}
}
}
public class StackOverflow {
public static void main(String[] sr) throws IOException{
//Read a folder and files in it
File f = new File("D:/workspace");
if(!f.exists())
System.out.println("No File/Dir");
if(f.isDirectory()){// a directory!
for(File file :f.listFiles()){
System.out.println(file.getName());
}
}
//Read a file an save content to a StringBuiilder
File f1 = new File("D:/workspace/so.txt");
BufferedReader br = new BufferedReader(new FileReader(f1));
StringBuilder sb = new StringBuilder();
String line = "";
while((line=br.readLine())!=null)
sb.append(line+"\n");
System.out.println(sb);
}
}

Categories

Resources