How to get the contents of an InputStream? - java

I use the following method to get all .class files from an eclipse project. but the returned files are in InputStream format which I can not get the content.
public void setFileList(IContainer container) throws CoreException, IOException {
IResource [] members = container.members();
for (IResource member : members) {
if (member instanceof IContainer) {
setFileList((IContainer)member);
} else if (member instanceof IFile && member.isDerived()) {
IFile file = (IFile)member;
InputStream contents = file.getContents();
this.fileList.add(contents);
}
}
}
How can I get the contents of this InputStream in a string format or a txt file?

If you want to write it into a file then you can directly use apache.commons.io helper method:
final File outputFile = new File("test.txt");
FileUtils.copyInputStreamToFile(inputStream, outputFile);

Related

How to get a file without the extension in Java?

I'm saving images to my resources folder regardless of the extension, and I want to load them the same way. Example: I want to get the image named "foo" whether it is "foo.jpg" or "foo.png".
Right now I'm loading the image for each extension and returning it if it exists OR trying for the next extension if an exception is thrown like so:
StringBuilder relativePath = new StringBuilder().append("src/main/resources/static/images/").append("/")
.append(id).append("/").append(imageName);
File imageFile = null;
byte[] imageBytes = null;
try {
imageFile = new File(new StringBuilder(relativePath).append(".jpg").toString());
imageBytes = Files.readAllBytes(imageFile.toPath());
} catch (IOException e) {
}
if (imageBytes == null) {
imageFile = new File(relativePath.append(".png").toString());
imageBytes = Files.readAllBytes(imageFile.toPath());
}
I feel like it's not the best way to do that, is there a way to load an image by its name and regardless of the extension?
You need to check it the file exists
File foo = new File("foo.jpg");
if (!foo.exists) {
foo = new File("foo.png");
}
But if you really want to load without using the extension, then you could list the files in directory that match a given pattern.
File dir = new File("/path/to/images/dir/");
File [] files = dir.listFiles(new FilenameFilter() {
#Override
public boolean accept(File dir, String name) {
return name.matches("foo\\.(jpg|png)");
}
});
File foo = files[0];

Accessing an external file

I'm looking to reaccess a file created in android studio. I found the following code snippet on stack exchange
File root = android.os.Environment.getExternalStorageDirectory();
// See http://stackoverflow.com/questions/3551821/android-write-to-sd-card-folder
File dir = new File(root.getAbsolutePath() + "/download");
File file = new File(dir, "myData.txt");
From my understanding this creates a file called "myData.txt" in the download folder. What im looking to do is pass "file" into a function in another method like so
public void onLocationChanged(Location location) {
ArrayList<Location> list = new ArrayList<>();
list.add(location);
GPX.writePath(file,"hello",list);
}
How do I go about creating a file variable that acesses the txt file without actually creating a new file?
File root = android.os.Environment.getExternalStorageDirectory();
// See http://stackoverflow.com/questions/3551821/android-write-to-sd-card-folder
File dir = new File(root.getAbsolutePath() + "/download");
File file = new File(dir, "myData.txt");
Actually it does not create a physical file. It just creates an object in memory (referenced by file).
You can then use the reference in your method to write to a physical file, like so:
public void onLocationChanged(File location) throws IOException {
ArrayList<File> list = new ArrayList<>();
list.add(location);
writeToFile("Text", location);
}
private static void writeToFile(String text, File file)
throws IOException {
try(BufferedWriter writer = new BufferedWriter(new FileWriter(file))) {
writer.write(text);
}
}
Update 2
If you want to use the reference in your method, you can pass the file reference to your method which should have some code to write the text into the actual file:
GPX.writePath(file,"hello",list);
...
public static void writePath(File file, String n, List<Location> points) throws IOException {
...
try(BufferedWriter writer = new BufferedWriter(new FileWriter(file))) {
writer.write(n);
}
}

How can I read a path from .txt in java

I have a txt file. This contains a directory (H: /). I want to read this directory. There are also a few csv files in the directory. I would like to see only the csv-files. My Java code contains everything relevant, I think. Now he does not find the text file. The text file is located in the project folder in Eclipse (so I used a relative path)
Where is my mistake?
EDIT: I make a common example of my problem
public class AllFiles {
public static void main(String[]args) throws IOException
{
File dir = new File("C:/Users/Example/Main/Test.txt");
getAllFiles(dir);
} private static void getAllFiles(File dir) throws IOException {
// Read from the file
BufferedReader br = new BufferedReader(new FileReader(dir));
String path = br.readLine();
br.close();
File[] fileArray = new File (line).listFiles(new FilenameFilter() {
//only data with .csv were shown
public boolean accept(File dir, String name) {
return name.endsWith(".csv");
}
});
for(File f : fileArray){
if(f.isDirectory())
getAllFiles(f);
if(f.isFile()){
System.out.println(f.getName());
}
}
}
}
You never assign the content of the file to the variable line.
Change String line;
br.readLine(); to String line = br.readLine();
The next error is that you are try to list files from ".../Users/example/Test.txt". Whyt you want to try is:
File[] fileArray = new File(line).listFiles(...

How to copy file from directory to another Directory in Java

I am using JDK 6.
I have 2 folders names are Folder1 and Folder2.
Folder1 have the following files
TherMap.txt
TherMap1.txt
TherMap2.txt
every time Folder2 have only one file with name as TherMap.txt.
What I want,
copy any file from folder1 and pasted in Folder2 with name as TherMap.txt.If already TherMap.txt exists in Folder2, then delete and paste it.
for I wrote the following code.but it's not working
public void FileMoving(String sourceFilePath, String destinationPath, String fileName) throws IOException {
File destinationPathObject = new File(destinationPath);
File sourceFilePathObject = new File(sourceFilePath);
if ((destinationPathObject.isDirectory()) && (sourceFilePathObject.isFile()))
//both source and destination paths are available
{
//creating object for File class
File statusFileNameObject = new File(destinationPath + "/" + fileName);
if (statusFileNameObject.isFile())
//Already file is exists in Destination path
{
//deleted File
statusFileNameObject.delete();
//paste file from source to Destination path with fileName as value of fileName argument
FileUtils.copyFile(sourceFilePathObject, statusFileNameObject);
}
//File is not exists in Destination path.
{
//paste file from source to Destination path with fileName as value of fileName argument
FileUtils.copyFile(sourceFilePathObject, statusFileNameObject);
}
}
}
I call the above function in main()
//ExternalFileExecutionsObject is class object
ExternalFileExecutionsObject.FileMoving(
"C:/Documents and Settings/mahesh/Desktop/InputFiles/TMapInput1.txt",
"C:/Documents and Settings/mahesh/Desktop/Rods",
"TMapInput.txt");
While I am using FileUtils function, it showing error so I click on error, automatically new package was generated with the following code.
package org.apache.commons.io;
import java.io.File;
public class FileUtils {
public static void copyFile(File sourceFilePathObject,
File statusFileNameObject) {
// TODO Auto-generated method stub
}
}
my code not showing any errors,even it's not working.
How can I fix this.
Thanks
Use Apache Commons FileUtils
FileUtils.copyDirectory(source, desc);
Your code isn't working because in order to use the ApacheCommons solution you will have to download the ApacheCommons library found here:
http://commons.apache.org/
and add a reference to it.
Since you are using JRE 6 you can't use all the NIO file utilities, and despite everyone loving Apache Commons as a quick way to answer forum posts, you may not like the idea of having to add that utility on just to get one function. You can also use this code that uses a transferFrom method without using ApacheCommons.
public static void copyFile(File sourceFile, File destFile) throws IOException {
if (!destFile.exists()) {
destFile.createNewFile();
}
FileInputStream fIn = null;
FileOutputStream fOut = null;
FileChannel source = null;
FileChannel destination = null;
try {
fIn = new FileInputStream(sourceFile);
source = fIn.getChannel();
fOut = new FileOutputStream(destFile);
destination = fOut.getChannel();
long transfered = 0;
long bytes = source.size();
while (transfered < bytes) {
transfered += destination.transferFrom(source, 0, source.size());
destination.position(transfered);
}
} finally {
if (source != null) {
source.close();
} else if (fIn != null) {
fIn.close();
}
if (destination != null) {
destination.close();
} else if (fOut != null) {
fOut.close();
}
}
}
When you upgrade to 7, you will be able to do the following
public static void copyFile( File from, File to ) throws IOException {
Files.copy( from.toPath(), to.toPath() );
}
reference:
https://gist.github.com/mrenouf/889747
Standard concise way to copy a file in Java?

How to include an XML database into a jar file and access to it?

Currently, I can only make my app access to the XML database when the jar file and XML file in the same directory, and what I hope is that there is only one single jar file which includes the XML file. How can I do that?
private String getXmlPath() {
String url = "";
try {
String cp = "Data\\QuestionList.xml";
File f = new File(ClassLoader.getSystemResource("\\").toURI().getPath());
url += f.getPath() + "\\" + cp;
} catch (URISyntaxException ex) {
url="QuestionList.xml";
}
System.out.println(url);
return url;
}
public void classifyQuestionnaire(String path)
throws FileNotFoundException, XMLStreamException, JAXBException {
// Parse the data, filtering out the start elements
XMLInputFactory xmlif = XMLInputFactory.newInstance();
FileReader fr = null;
if (path == null) {
fr = new FileReader(getXmlPath());
} else {
fr = new FileReader(path);
}
XMLEventReader xmler = xmlif.createXMLEventReader(fr);
EventFilter filter = new EventFilter() {
#Override
public boolean accept(XMLEvent event) {
return event.isStartElement();
}
};
You can include xml file into the jar. These non-class files are usually called "resource". It depends on how you're creating the jar, but it's usually straight forward. See Java: Load a resource contained in a jar for reading the resource.

Categories

Resources