Java Commons IO append multiple files - java

I am using Commons IO to download files from the internet.
This is the method i am using:
public void getFile(String url){
File f = new File("C:/Users/Matthew/Desktop/hello.txt");
PrintWriter pw = new PrintWriter(f);
pw.close();
URL url1;
try {
url1 = new URL(url);
FileUtils.copyURLToFile(url1, f);
} catch (MalformedURLException e1) {
e1.printStackTrace();
}catch (IOException e1){
e1.printStackTrace();
}
}
Is there a way i can download multiple files using this method and have them all save to the hello.txt file? Using the above method, everything gets overwritten and the last file downloaded will be the one added to the hello.txt file.
Basically, is there a way i can store multiple file downloads in one file.
Thanks.

There is no way using FileUtils. However, if you want to use Apache Commons, I'd suggest you do the following:
File f = new File("C:/Users/Matthew/Desktop/hello.txt");
URL url1;
try {
url1 = new URL(url);
IOUtils.copy(url1.openStream(), new FileOutputStream(f, true));
} catch (MalformedURLException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
which does more or less the same thing, but uses append mode on the FileOutputStream.

Related

Generate doc use docx4j, it gose different on windows and linux server

when I use docx4j to generate doc from HTML and output through java servlet, it works well on Windows system, I can download and open the doc file normally.
When I put the project on Linux server, I can also download the doc file, but when openging file, it alert that the file is broken. I must click the confirm and restore the file.then open it normally.
my core code is like this.
how can i get the same result as windows?
code in jsp:
String vhtml = DownHtml2DocUtil.replaceSvgData2Base64(request);
response.reset();
response.setContentType("application/octet-stream");//设置为字节流
OutputStream output = null;
try {
output = response.getOutputStream();
response.addHeader("Content-Disposition", "attachment;filename=" + System.currentTimeMillis() + ".doc");
DownHtml2DocUtil.genDocFromHtml(vhtml, output);
} catch (Exception e) {
} finally {
try {
if (output != null) {
output.close();
}
} catch (Exception e) {
}
}
response.flushBuffer();
out.clear();
out = pageContext.pushBody();
code in java like this:
public static void genDocFromHtml(String html, OutputStream out)
throws EMPException {
try {
WordprocessingMLPackage wordMLPackage;
wordMLPackage = WordprocessingMLPackage.createPackage();
XHTMLImporterImpl XHTMLImporter = new XHTMLImporterImpl(
wordMLPackage);
wordMLPackage.getMainDocumentPart().getContent()
.addAll(XHTMLImporter.convert(html, "utf-8"));
// wordMLPackage.save(out); -- i tried both method
new Save(wordMLPackage).save(out);
} catch (InvalidFormatException e) {
throw new EMPException(e);
} catch (Docx4JException e) {
throw new EMPException(e);
} catch (Exception e) {
e.printStackTrace();
}
}
any suggestion will be appreciate , thanks anyway;

How to place a file for jar and read it with FileInputStream

This is the code
public static void readCharacters() {
try (FileInputStream fi = new FileInputStream("main/characters.dat"); ObjectInputStream os = new ObjectInputStream(fi)) {
characterList = (LinkedList<Character>) os.readObject();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
This is the structure:
And this is the Error
java.io.FileNotFoundException: main\characters.dat (The system cannot find the path specified)
What I want is to include the characters.dat file in my jar, and be able to read and write it while the program runs. Is there a different way to write the path? or to put the .dat file in a different position.
Also the writing method:
public static void writeCharacters() {
try (FileOutputStream fs = new FileOutputStream("main/characters.dat"); ObjectOutputStream os = new ObjectOutputStream(fs)) {
System.out.println("Writing Characters...");
os.writeObject(characterList);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
You can't. You can do one or the other. JAR files are not file systems, and their entries are not files. You can read it with an input stream:
InputStream in = this.getClass().getResourceAsStream("/main/characters.dat");
Check it for null before proceeding.
The jar is for read-only resources. You can use it for the initial file, as a kind of template.
Path path = Paths.get(System.getProperty("user.home") + "/myapp/chars.dat");
Files.mkdirs(path.getParentPath());
if (!Files.exists()) {
try (InputStream in =
Controller.class.getResourceAsStream("/main/characters.dat")) {
Files.copy(in, path);
}
}
The above copies the initial.dat resource from the jar to the user's home "myapp" directory, which is a common solution.
System.getProperty("user.dir") would the running directory. One can also take the jar's path:
URL url = Controller.class.getResource("/main/characters.dat");
String s = url.toExternalForm(); // "jar:file:/.... /xxx.jar!/main/characters.dat"
From that you can also construct the jar's directory. Mind to check Windows, Linux, spaces and such.
URL url = Controller.class.getProtectionDomain().getCodeSource().getLocation();
The solution above risks a NullPointerException, and works a bit differenly running inside the IDE or stand-alone.
Important note:
When using getResourceAsStream, you must start your path by slash /, this specifies the root of your jar, .getResourceAsStream("/file.txt");
In my case my file was a function argument, String filename, I had to do it like this:
InputStream in = this.getClass().getResourceAsStream("/" + filename);

Writing and reading from txt file android

I know that this is a widely discussed question , but I am really confused with those examples provided on android developers manual .
So , I have a "source.txt" in my res/raw folder .For example I want to write 2 lines in it(for ex. Hello\nWorld) and then read them from another activity. Can anyone write the source code for this , please.
You should replace your .txt file to your extornal or internal storage.And You must give permission for write text from androidManifest.xml
for reading file you can do this
public String readFile(String filePath) {
String jString = null;
StringBuilder builder = new StringBuilder();
File yourFile = new File("/sdcard/" + filepath);
if (yourFile.exists()) {
Log.i("file", "file founded");
BufferedReader bufferedReader = null;
try {
bufferedReader = new BufferedReader(new FileReader(yourFile));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String row = "";
try {
while ((row = bufferedReader.readLine()) != null) {
builder.append(row + "\n");
}
bufferedReader.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
jString = builder.toString();
}
else {
Log.i("FAIL", "FILE NOT FOUND");
}
return jString;
}
for writing file you can use this
public void writetoFile(String filename,String text) {
File file = new File("/sdcard/" + filename);
if (!file.exists())
try {
file.createNewFile();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
FileWriter fileWriter;
try {
//you can change second parametre true or false this is about append or clean and write
fileWriter = new FileWriter(file, false);
BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
bufferedWriter.append(jsonText);
bufferedWriter.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Whatever is in your APK file is read-only, therefore you are unable to write to file stored in res/raw source folder as it is still in your APK. if you want to work on file shipped with your app, you need to copy if to internal storage or SD card from APK first so that would allow you to alter the content.
Every file in your apk is read only, so you need to create the file in your internal storage or SD Card. If you just want to send small amount to of data to second activity, you can send data along with intent or use sharedPreference.
If you really want to read and write data to/from SD card then you need to use FileInputStream and OutputStreamWriter to read/write data to a file. Check this tutorial here to see how it's done. http://www.java-samples.com/showtutorial.php?tutorialid=1523

Why isn't a new created file local?

I have the problem, that I create a new file in a Java program, but I always get an exception, that the new created file is not local, when I try to open it on the eclipse project explorer view.
The code where I create it is as follows:
IWorkspaceRoot workspaceRoot = ResourcesPlugin.getWorkspace().getRoot();
IProject project = workspaceRoot.getProject(projectName);
FileUtil myFile = new FileUtil();
if (!project.getFile(FILE_NAME).exists()) {
IFile newFile = project.getFile("conf.txt");
FileInputStream fileStream = null;
try {
String temp = project + "/conf.txt";
temp = temp.substring(2);
fileStream = new FileInputStream(temp);
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
newFile.create(fileStream, false, null);
} catch (CoreException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
// create closes the file stream, so no worries.
try {
myFile.writeTextFile(FILE_NAME, "Seconds", output);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
FileUtil is a class which only implements the methods write and read for the file.
The Exception I get when I try to open it begins with:
org.eclipse.core.internal.resources.ResourceException: Resource '/ProjectE1/conf.txt' is not local.
at org.eclipse.core.internal.resources.Resource.checkLocal(Resource.java:353)
at org.eclipse.core.internal.resources.File.getContentDescription(File.java:264)
at org.eclipse.core.internal.propertytester.FilePropertyTester.testContentType(FilePropertyTester.java:108)
I somehow have to get a relative path during the runtime. Because I am opening a new instance of eclipse in the program, where I can see the Project in the Project Explorer but can't open the conf.txt file because it is not local.
It looks like your resource is an absolute path to /ProjectE1/conf.txt, I'm confused why you are not using java.io.
This will help you understand relative paths, I think this may be where you are wanting to put your conf file.
File file = new File("conf.txt");
if(!file.createNewFile()){
//err
}
System.out.println(file.getAbsolutePath());
I had similar issue. This is how I fixed.
First created file in local file system (using java.io)
Did project refresh
Reload the file
File file = new File(project.getWorkspace().getRoot().getLocation() + project.getFullPath().toString() + "/relative_path_of_my_file");
file.createNewFile();
project.refreshLocal(IProject.DEPTH_INFINITE, null);
keywordFile = project.getFile("/relative_path_of_my_file");

Android MediaPlayer needs file at installation

I am dynamically generating midi files (in cache dir) with an android app.
After generation, I play the file with MediaPlayer within the same app.
When running the app for the first time, it already needs the file to be there in the cache directory (the app crashes). It works on the emulator if I use the filemanager to put a dummy file there first. How can I circumvent this?
I need the app to run on a tablet for the first time, without requiring the file.
I am using these commands now:
try {
filePath = getCacheDir() + "/optimuse" + song + ".mid";
file = new File(filePath);
inputStream = new FileInputStream(file);
if (inputStream.getFD().valid()) {
System.out.println("Valid!");
}
} catch (Exception e1) {
e1.printStackTrace();
System.exit(-1);
}
try {
mediaPlayer = new MediaPlayer();
mediaPlayer.setDataSource(inputStream.getFD());
inputStream.close();
} catch (Exception e1) {
e1.printStackTrace();
System.exit(-1);
}
try {
mediaPlayer.prepare();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Is there any way around this?
Thanks!
Maybe check whether the file exists before using it? You can achieve this using the File#exists() method.
First, you use the Context#getFileStreamPath(String) method - where the String is the filename of the file you are trying to access. Then you can call File#exists() on the returned object.

Categories