Writing Console Output to File in Java - java

So I was wondering if it was possible to write all the console output to a separate file outside of Java? I know about the Printwriter and Filewriter method. However, in my experience those would work if I was using them all within one method, but I don't think I can do that with the code I have right now. Below is what I have...
Java Code
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import org.xml.sax.*;
import org.xml.sax.helpers.DefaultHandler;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
public class XMLTagParser extends DefaultHandler
{
private int i;
public XMLTagParser()
{
traverse(new File("C:/Documents and Settings/user/workspace/Intern Project/Proposals/Converted Proposals/Extracted Items"));
}
private static final class SaxHandler extends DefaultHandler
{
private StringBuffer buffer;
private String heading;
private boolean inHeading;
public void startElement(String uri, String localName, String qName, Attributes attrs)
{
if ("w:pStyle".equals(qName))
{
String val = attrs.getValue("w:val");
if (val.contains("Heading"))
{
if (isHeading(val))
{
System.out.println(val);
inHeading = true;
}
}
}
if("w:t".equals(qName))
{
if (inHeading == true)
{
buffer = new StringBuffer();
}
}
}
public void characters(char buff[], int offset, int length) throws SAXException
{
String s = new String(buff, offset, length);
if(buffer != null)
{
buffer.append(s);
heading = heading += s;
}
}
public void endElement(String uri, String localName, String qName)
{
buffer = null;
//if the qName is "w:p" and it is in the heading, print out the heading and then reset
if ("w:p".equals(qName) && inHeading == true)
{
System.out.println(heading);
heading = "";
inHeading = false;
}
}
// method to verify whether element is an actual heading
private static boolean isHeading(String heading)
{
String headingNumber = heading.substring(7,8);
String headingName = heading.substring(0,7);
if (headingName.equals("Heading"))
{
if (headingNumber.equals("1")
|| headingNumber.equals("2")
|| headingNumber.equals("3")
|| headingNumber.equals("4")
|| headingNumber.equals("5")
|| headingNumber.equals("6"))
{
return true;
}
}
return false;
}
}
/*private void writeFile(File file)
{
try
{
PrintWriter out = new PrintWriter(new FileWriter(file + "/" + i++));
out.close();
}
catch (IOException e)
{
e.printStackTrace(System.out);
}
}*/
private void traverse(File directory)
{
//Get all files in directory
File[] files = directory.listFiles();
for (File file : files)
{
if (file.getName().equals("document.xml"))
{
try
{
// creates and returns new instance of SAX-implementation:
SAXParserFactory factory = SAXParserFactory.newInstance();
// create SAX-parser...
SAXParser parser = factory.newSAXParser();
// prints out the current working proposal, traversing up the directory structure
System.out.println(file.getParentFile().getParentFile().getName());
// .. define our handler:
SaxHandler handler = new SaxHandler();
// and parse:
parser.parse(file.getAbsolutePath(), handler);
try
{
// instantiates new printwriter which writes out to a file
PrintWriter out = new PrintWriter(new FileWriter(file.getParentFile().getParentFile() + "/" + i++ + ".txt"));
out.close();
}
catch (IOException e)
{
e.printStackTrace(System.out);
}
}
catch (Exception ex)
{
ex.printStackTrace(System.out);
}
}
else if (file.isDirectory())
{
//It's a directory so (recursively) traverse it
traverse(file);
}
}
}
}
So I've instantiated the printwriter in there, but obviously it's no good if I have nothing to write to it. So I'm not really sure how I can get what's printing out the console to be written to that file. Any ideas? Thanks in advance.

If you really want to you can redirect System.out to any PrintStream like this:
PrintStream stream = new PrintStream("filename.txt");
System.setOut(stream);

If you get into rolling your own file logger you'll spend more time dealing with io issues, rolling files, file sizes, ect. You should use log4j instead! It will handle things like this and make your logging more flexible. It's pretty much the standard for java logging.

The System.out is basically an OutputStream; which by default points to the console. Instead, you could just create a new FileOutputStream instance pointing to the file of your choice, and identify this stream by setting it through System.setOut. That will do it for you, throughout the life-cycle of the program/application. Check this link for a complete code.

Instead of using System.out, you could use a FileWriter, write to it and flush it. It is unclear, why you increment i in your code. I guess you want to write everything to just one file.
Also, it looks like you never write to the Writer that you initialize.

You could keep using System.out, and redirect it using ">" to the file when you invoke the application. You can still retain stderr for direct console output.
Or do you mean something else when you write "outside java"?

Related

Process a ZIPped XML file in Java [duplicate]

I am trying to create a simple java program which reads and extracts the content from the file(s) inside zip file. Zip file contains 3 files (txt, pdf, docx). I need to read the contents of all these files and I am using Apache Tika for this purpose.
Can somebody help me out here to achieve the functionality. I have tried this so far but no success
Code Snippet
public class SampleZipExtract {
public static void main(String[] args) {
List<String> tempString = new ArrayList<String>();
StringBuffer sbf = new StringBuffer();
File file = new File("C:\\Users\\xxx\\Desktop\\abc.zip");
InputStream input;
try {
input = new FileInputStream(file);
ZipInputStream zip = new ZipInputStream(input);
ZipEntry entry = zip.getNextEntry();
BodyContentHandler textHandler = new BodyContentHandler();
Metadata metadata = new Metadata();
Parser parser = new AutoDetectParser();
while (entry!= null){
if(entry.getName().endsWith(".txt") ||
entry.getName().endsWith(".pdf")||
entry.getName().endsWith(".docx")){
System.out.println("entry=" + entry.getName() + " " + entry.getSize());
parser.parse(input, textHandler, metadata, new ParseContext());
tempString.add(textHandler.toString());
}
}
zip.close();
input.close();
for (String text : tempString) {
System.out.println("Apache Tika - Converted input string : " + text);
sbf.append(text);
System.out.println("Final text from all the three files " + sbf.toString());
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SAXException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (TikaException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
If you're wondering how to get the file content from each ZipEntry it's actually quite simple. Here's a sample code:
public static void main(String[] args) throws IOException {
ZipFile zipFile = new ZipFile("C:/test.zip");
Enumeration<? extends ZipEntry> entries = zipFile.entries();
while(entries.hasMoreElements()){
ZipEntry entry = entries.nextElement();
InputStream stream = zipFile.getInputStream(entry);
}
}
Once you have the InputStream you can read it however you want.
As of Java 7, the NIO АРI provides a better and more generic way of accessing the contents of ZIP or JAR files. Actually, it is now a unified API which allows you to treat ZIP files exactly like normal files.
In order to extract all of the files contained inside of a ZIP file in this API, you'd do as shown below.
In Java 8
private void extractAll(URI fromZip, Path toDirectory) throws IOException {
FileSystems.newFileSystem(fromZip, Collections.emptyMap())
.getRootDirectories()
.forEach(root -> {
// in a full implementation, you'd have to
// handle directories
Files.walk(root).forEach(path -> Files.copy(path, toDirectory));
});
}
In Java 7
private void extractAll(URI fromZip, Path toDirectory) throws IOException {
FileSystem zipFs = FileSystems.newFileSystem(fromZip, Collections.emptyMap());
for (Path root : zipFs.getRootDirectories()) {
Files.walkFileTree(root, new SimpleFileVisitor<Path>() {
#Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs)
throws IOException {
// You can do anything you want with the path here
Files.copy(file, toDirectory);
return FileVisitResult.CONTINUE;
}
#Override
public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs)
throws IOException {
// In a full implementation, you'd need to create each
// sub-directory of the destination directory before
// copying files into it
return super.preVisitDirectory(dir, attrs);
}
});
}
}
Because of the condition in while, the loop might never break:
while (entry != null) {
// If entry never becomes null here, loop will never break.
}
Instead of the null check there, you can try this:
ZipEntry entry = null;
while ((entry = zip.getNextEntry()) != null) {
// Rest of your code
}
Sample code you can use to let Tika take care of container files for you.
http://wiki.apache.org/tika/RecursiveMetadata
Form what I can tell, the accepted solution will not work for cases where there are nested zip files. Tika, however will take care of such situations as well.
My way of achieving this is by creating ZipInputStream wrapping class that would handle that would provide only the stream of current entry:
The wrapper class:
public class ZippedFileInputStream extends InputStream {
private ZipInputStream is;
public ZippedFileInputStream(ZipInputStream is){
this.is = is;
}
#Override
public int read() throws IOException {
return is.read();
}
#Override
public void close() throws IOException {
is.closeEntry();
}
}
The use of it:
ZipInputStream zipInputStream = new ZipInputStream(new FileInputStream("SomeFile.zip"));
while((entry = zipInputStream.getNextEntry())!= null) {
ZippedFileInputStream archivedFileInputStream = new ZippedFileInputStream(zipInputStream);
//... perform whatever logic you want here with ZippedFileInputStream
// note that this will only close the current entry stream and not the ZipInputStream
archivedFileInputStream.close();
}
zipInputStream.close();
One advantage of this approach: InputStreams are passed as an arguments to methods that process them and those methods have a tendency to immediately close the input stream after they are done with it.
i did mine like this and remember to change url or zip files
jdk 15
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Scanner;
import java.util.stream.Stream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.io.*;
import java.util.*;
import java.nio.file.Paths;
class Main {
public static void main(String[] args) throws MalformedURLException,FileNotFoundException,IOException{
String url,kfile;
Scanner getkw = new Scanner(System.in);
System.out.println(" Please Paste Url ::");
url = getkw.nextLine();
System.out.println("Please enter name of file you want to save as :: ");
kfile = getkw.nextLine();
getkw.close();
Main Dinit = new Main();
System.out.println(Dinit.dloader(url, kfile));
ZipFile Vanilla = new ZipFile(new File("Vanilla.zip"));
Enumeration<? extends ZipEntry> entries = Vanilla.entries();
while(entries.hasMoreElements()){
ZipEntry entry = entries.nextElement();
// String nextr = entries.nextElement();
InputStream stream = Vanilla.getInputStream(entry);
FileInputStream inpure= new FileInputStream("Vanilla.zip");
FileOutputStream outter = new FileOutputStream(new File(entry.toString()));
outter.write(inpure.readAllBytes());
outter.close();
}
}
private String dloader(String kurl, String fname)throws IOException{
String status ="";
try {
URL url = new URL("URL here");
FileOutputStream out = new FileOutputStream(new File("Vanilla.zip")); // Output File
out.write(url.openStream().readAllBytes());
out.close();
} catch (MalformedURLException e) {
status = "Status: MalformedURLException Occured";
}catch (IOException e) {
status = "Status: IOexception Occured";
}finally{
status = "Status: Good";}
String path="\\tkwgter5834\\";
extractor(fname,"tkwgter5834",path);
return status;
}
private String extractor(String fname,String dir,String path){
File folder = new File(dir);
if(!folder.exists()){
folder.mkdir();
}
return "";
}
}

I want to create a class to create a file, and use main class to check if that file is created, but my code fail. (Java)

public class Fileverifynanoha
{
private File fileext;
private Path filepath;
public Fileverifynanoha()//this class wants to create a file, write something, and close it.
{
filepath = Paths.get("./txttest.txt");
Charset charset = Charset.forName("US-ASCII");
String s = "Takamachi Nanoha. Shirasaki Tsugumi.!";
try (BufferedWriter filewriter = Files.newBufferedWriter(filepath,charset))
{
filewriter.write(s,0,s.length()-1);
}
catch(IOException e)
{
System.err.println(e);
}
}//end of this class
/**
* #param args the command line arguments
*/
public static void main(String[] args)//the main method will check if this file contains(created), if so, return exist. if not, return doesnt exist.
{
if (filetxt.exists()&&!filetxt.isDirectory())//object does not create any real thing, therefore nothing true will return.
{
System.out.println("File exist.");
}
else
{
System.out.println("File does not exist.");
}
}
}
Here is the code. I want to use the class I create to create a file, write something. Then, I use main class to check if that file exist.
However, I don't know why, but the main class does not recognise my (maybe) created file. Could anyone tell me how to link them together?
I know there may be some minor bugs in this program. I will fix that later.
Thanks.
You never called your constructor.
public static void main(String[] args)//the main method will check if this file contains(created), if so, return exist. if not, return doesnt exist.
{
Fileverifynanoha fvn = new Fileverifynanoha();
if (fvn.filetxt.exists()&&!fvn.filetxt.isDirectory())
{
System.out.println("File exist.");
}
else
{
System.out.println("File does not exist.");
}
}
}
Your issues:
Didn't create instance of class.
Didn't init File file, so it would be null always.
Better use utf-8 for plain text file.
Try this:
import java.io.BufferedWriter;
import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
public class Fileverifynanoha {
private File file;
private Path path;
public Fileverifynanoha(String fp) {
this.path = Paths.get(fp);
this.file = path.toFile();
}
public void createFile()// this class wants to create a file, write something, and close it.
{
Charset charset = Charset.forName("UTF-8");
String s = "Takamachi Nanoha. Shirasaki Tsugumi.!";
BufferedWriter filewriter = null;
try {
filewriter = Files.newBufferedWriter(path, charset);
filewriter.write(s, 0, s.length() - 1);
filewriter.close();
} catch (IOException e) {
System.err.println(e);
}
}// end of this class
/**
* #param args
* the command line arguments
*/
public static void main(String[] args)// the main method will check if this file contains(created), if so, return exist. if not, return doesnt exist.
{
Fileverifynanoha f = new Fileverifynanoha("./txttest.txt");
f.createFile();
if (f.file.exists() && !f.file.isDirectory())// object does not create any real thing, therefore nothing true will return.
{
System.out.println("File exist.");
} else {
System.out.println("File does not exist.");
}
}
}

How to read/write an object that has linked lists in a file

I have these classes: "MyClass1", "MyClass2", "MyClass3" and "MyMainClass",
public class MyMainClass implements Serializable {
private String att1, att2, att3;
private int att4, att5, att6;
private LinkedList <MyClass1> myClass1List = new LinkedList<MyClass1>();
private LinkedList <MyClass2> myClass2List = new LinkedList<MyClass2>();
private LinkedList <MyClass3> myClass3List = new LinkedList<MyClass3>();
}
My program create registers (Objects) of "MyMainClass" and deposit it in a LinkedList. I want to save the LinkedList of the objects in a file to get them after i reopen my program. What's the way to do it? I have tried with ObjectOutputStream, but doesn't work. Thanks.
Edit:
My code to add an object(I just read an example and tried):
public static void addObject (MyMainClass p) {
try {
outputStream = new ObjectOutputStream(new FileOutputStream("myfile.dat"));
outputStream.writeObject(p);
} catch (FileNotFoundException ex) {
ex.printStackTrace();
System.exit(1);
} catch (IOException ex) {
ex.printStackTrace();
System.exit(1);
} finally {
try {
if (outputStream != null) {
outputStream.flush();
outputStream.close();
}
} catch (IOException ex) {
ex.printStackTrace();
System.exit(1);
}
}
}
Note: "MyClass1", "MyClass2", "MyClass3" are Serializable.
I would make "myClass1", "myClass2", and "myClass3" Serializable, then wrap myClass1List, myClass2List, and myClass3List (and any other data you want to save) in another serializable class so you can use serialization/deserialization to save and restore all of the program state at once.
Unless myMainClass is that wrapper, in which case you need to declare that they all implement Serializable.
myMainClass isn't marked Serializable. Also, are myClass1, myClass2, and myClass3 serializable as well? If not, they should be.
On another note, please follow Java naming conventions; class name should start with an uppercase letter.
UPDATE
Are you sure that it's not writing to the file, or is it that the code is throwing exceptions that you cannot see?
In all your catch blocks, you have System.exit(1), which gives you absolutely no information about any exceptions that are happening; you're essentially swallowing them. You should at least print out the stacktrace (ex.printStackTrace()) so you can see what is going wrong.
I used following for my highschool project long time ago. Due to my poor English skills I do not really understand what class you wish to save and load (LinkedList or myMainClass), but I used this solution to successfully store and load any of my custom objects. I hope you find it handy.
Usage:
myMainClass object;
//
// ... your code fillin up the content of object
//
MyIO io = new MyIO();
io.save("", "myfile.dat", object); // "" as first argument will make java use current working directory
// to load the object:
myMainObject object = (myMainObject) io.load("", "myfile.dat");
Source:
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;
import java.io.FileOutputStream;
import java.io.FileInputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.IOException;
public class MyIO {
// String path - path to the directory where the file is supposed to be saved.
// String filename - the name of the file
// Object data - object that you wish to save in the file. In your case "myMainClass"
public void save(String path, String filename, Object data) {
try {
FileOutputStream fos = new FileOutputStream(path + filename, false);
GZIPOutputStream gzos = new GZIPOutputStream(fos);
ObjectOutputStream out = new ObjectOutputStream(gzos);
out.writeObject(data);
out.flush();
out.close();
} catch (IOException e) {
System.out.println(e);
}
}
// String path - path to the directory where the file is stored
// String filename - the name of the file
// The function returns java object which can be cast to myMainClass.
public Object load(String path, String filename) {
try {
FileInputStream fis = new FileInputStream(path + filename);
GZIPInputStream gzis = new GZIPInputStream(fis);
ObjectInputStream in = new ObjectInputStream(gzis);
Object data = in.readObject();
in.close();
return data;
} catch (Exception e) {
System.out.println(e);
}
return null;
}
}

I/O operations on file

I have a requirement, for example, there will be number of .txt files in one loation c:\onelocation. I want to write the content to another location in txt format. This part is pretty easy and straight forward. But there is speed breaker here.
There will be time interval take 120 seconds. Read the files from above location and write it to another files with formate txt till 120secs and save the file with name as timestamp.
After 120sec create one more files with that timestamp but we have to read the files were cursor left in previous file.
Please can you suggest any ideas, if code is provided that would be also appreciable.
Thanks Damu.
How about this? A writer that automatically changes where it is writing two every 120 seconds.
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
public class TimeBoxedWriter extends Writer {
private static DateFormat FORMAT = new SimpleDateFormat("yyyyDDDHHmm");
/** Milliseconds to each time box */
private static final int TIME_BOX = 120000;
/** For testing only */
public static void main(String[] args) throws IOException {
Writer w = new TimeBoxedWriter(new File("."), "test");
// write one line per second for 500 seconds.
for(int i = 0;i < 500;i++) {
w.write("testing " + i + "\n");
try {
Thread.sleep(1000);
} catch (InterruptedException ie) {}
}
w.close();
}
/** Output folder */
private File dir_;
/** Timestamp for current file */
private long stamp_ = 0;
/** Stem for output files */
private String stem_;
/** Current output writer */
private Writer writer_ = null;
/**
* Create new output writer
*
* #param dir
* the output folder
* #param stem
* the stem used to generate file names
*/
public TimeBoxedWriter(File dir, String stem) {
dir_ = dir;
stem_ = stem;
}
#Override
public void close() throws IOException {
synchronized (lock) {
if (writer_ != null) {
writer_.close();
writer_ = null;
}
}
}
#Override
public void flush() throws IOException {
synchronized (lock) {
if (writer_ != null) writer_.flush();
}
}
private void rollover() throws IOException {
synchronized (lock) {
long now = System.currentTimeMillis();
if ((stamp_ + TIME_BOX) < now) {
if (writer_ != null) {
writer_.flush();
writer_.close();
}
stamp_ = TIME_BOX * (System.currentTimeMillis() / TIME_BOX);
String time = FORMAT.format(new Date(stamp_));
writer_ = new FileWriter(new File(dir_, stem_ + "." + time
+ ".txt"));
}
}
}
#Override
public void write(char[] cbuf, int off, int len) throws IOException {
synchronized (lock) {
rollover();
writer_.write(cbuf, off, len);
}
}
}
Use RamdomAccessFile in java to move the cursor within the file.
Before start copying check the file modification/creation(in case of new files) time, if less than 2 mins then only start copying or else skip it.
Keep a counter of no.of bytes/lines read for each file. move the cursor to that position and read it from there.
You can duplicate the file rather than using reading and writing operations.
sample code:
FileChannel ic = new FileInputStream("<source file location>")).getChannel();
FileChannel oc = new FileOutputStream("<destination location>").getChannel();
ic.transferTo(0, ic.size(), oc);
ic.close();
oc.close();
HTH
File io is simple in java, here is an example I found on the web of copying a file to another file.
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class Copy {
public static void main(String[] args) throws IOException {
File inputFile = new File("farrago.txt");
File outputFile = new File("outagain.txt");
FileReader in = new FileReader(inputFile);
FileWriter out = new FileWriter(outputFile);
int c;
while ((c = in.read()) != -1)
out.write(c);
in.close();
out.close();
}
}

How to read a text-file resource into Java unit test?

I have a unit test that needs to work with XML file located in src/test/resources/abc.xml. What is the easiest way just to get the content of the file into String?
Finally I found a neat solution, thanks to Apache Commons:
package com.example;
import org.apache.commons.io.IOUtils;
public class FooTest {
#Test
public void shouldWork() throws Exception {
String xml = IOUtils.toString(
this.getClass().getResourceAsStream("abc.xml"),
"UTF-8"
);
}
}
Works perfectly. File src/test/resources/com/example/abc.xml is loaded (I'm using Maven).
If you replace "abc.xml" with, say, "/foo/test.xml", this resource will be loaded: src/test/resources/foo/test.xml
You can also use Cactoos:
package com.example;
import org.cactoos.io.ResourceOf;
import org.cactoos.io.TextOf;
public class FooTest {
#Test
public void shouldWork() throws Exception {
String xml = new TextOf(
new ResourceOf("/com/example/abc.xml") // absolute path always!
).asString();
}
}
Right to the point :
ClassLoader classLoader = getClass().getClassLoader();
File file = new File(classLoader.getResource("file/test.xml").getFile());
Assume UTF8 encoding in file - if not, just leave out the "UTF8" argument & will use the
default charset for the underlying operating system in each case.
Quick way in JSE 6 - Simple & no 3rd party library!
import java.io.File;
public class FooTest {
#Test public void readXMLToString() throws Exception {
java.net.URL url = MyClass.class.getResource("test/resources/abc.xml");
//Z means: "The end of the input but for the final terminator, if any"
String xml = new java.util.Scanner(new File(url.toURI()),"UTF8").useDelimiter("\\Z").next();
}
}
Quick way in JSE 7
public class FooTest {
#Test public void readXMLToString() throws Exception {
java.net.URL url = MyClass.class.getResource("test/resources/abc.xml");
java.nio.file.Path resPath = java.nio.file.Paths.get(url.toURI());
String xml = new String(java.nio.file.Files.readAllBytes(resPath), "UTF8");
}
Quick way since Java 9
new String(getClass().getClassLoader().getResourceAsStream(resourceName).readAllBytes());
Neither intended for enormous files though.
First make sure that abc.xml is being copied to your output directory. Then you should use getResourceAsStream():
InputStream inputStream =
Thread.currentThread().getContextClassLoader().getResourceAsStream("test/resources/abc.xml");
Once you have the InputStream, you just need to convert it into a string. This resource spells it out: http://www.kodejava.org/examples/266.html. However, I'll excerpt the relevent code:
public String convertStreamToString(InputStream is) throws IOException {
if (is != null) {
Writer writer = new StringWriter();
char[] buffer = new char[1024];
try {
Reader reader = new BufferedReader(
new InputStreamReader(is, "UTF-8"));
int n;
while ((n = reader.read(buffer)) != -1) {
writer.write(buffer, 0, n);
}
} finally {
is.close();
}
return writer.toString();
} else {
return "";
}
}
With the use of Google Guava:
import com.google.common.base.Charsets;
import com.google.common.io.Resources;
public String readResource(final String fileName, Charset charset) throws Exception {
try {
return Resources.toString(Resources.getResource(fileName), charset);
} catch (IOException e) {
throw new IllegalArgumentException(e);
}
}
Example:
String fixture = this.readResource("filename.txt", Charsets.UTF_8)
You can try doing:
String myResource = IOUtils.toString(this.getClass().getResourceAsStream("yourfile.xml")).replace("\n","");
Here's what i used to get the text files with text. I used commons' IOUtils and guava's Resources.
public static String getString(String path) throws IOException {
try (InputStream stream = Resources.getResource(path).openStream()) {
return IOUtils.toString(stream);
}
}
You can use a Junit Rule to create this temporary folder for your test:
#Rule public TemporaryFolder temporaryFolder = new TemporaryFolder();
File file = temporaryFolder.newFile(".src/test/resources/abc.xml");
OK, for JAVA 8, after a lot of debugging
I found that there's a difference between
URL tenantPathURI = getClass().getResource("/test_directory/test_file.zip");
and
URL tenantPathURI = getClass().getResource("test_directory/test_file.zip");
Yes, the / at the beginning of the path without it I was getting null!
and the test_directory is under the test directory.
Using Commons.IO, this method works from EITHER a instance method or a static method:
public static String loadTestFile(String fileName) {
File file = FileUtils.getFile("src", "test", "resources", fileName);
try {
return FileUtils.readFileToString(file, StandardCharsets.UTF_8);
} catch (IOException e) {
log.error("Error loading test file: " + fileName, e);
return StringUtils.EMPTY;
}
}

Categories

Resources