Suppose I have a .jar file that exports a temple.txt into directory ~/output. The code that does this is below. However suppose that this output folder is actually in home/workspace/temp/output. How do I use the File(..) constructor to send temple.txt to some completely different folder, such as home/Desktop/hello/ ?
public class main {
public static void main(String[] args) throws IOException {
String directory = "output";
FileWriter fstream;
BufferedWriter out;
File file = new File(directory, "temple.txt");
fstream = new FileWriter(file);
out = new BufferedWriter(fstream);
out.write(String.valueOf(1));
out.close();
}
}
Related
Class MakeDirectory contains the constructor, and in the constructor I created a directory and inside that directory I created a file. But I am unable to write anything to the newly created file, even though the file and directory have been generated successfully. Can anyone help me figure out why I am not able to write to the file Anything.txt?
public class MakeDirectory {
MakeDirectory() throws IOException{
// Creates Directory
File mydir= new File("MyDir");
mydir.mkdir();
// Creates new file object
File myfile = new File("MyDir","Anyfile.txt");
//Create actual file Anyfile.txt inside the directory
PrintWriter pr= new PrintWriter(myfile);
pr.write("This file is created through java");
}
public static void main(String args[]) throws IOException {
new MakeDirectory();
}
}
If you want to use PrintWriter you need to know that it is not automatically flushing. After you write you need to flush. Also, don't forget to close your PrintWriter!
PrintWriter pw = new PrintWriter(myFile);
pw.write("text");
pw.flush();
pw.close();
An approach available in Java 7 employs the try-with-resources construct. Using this feature, the code would look like the following:
try (PrintWriter pw = new PrintWriter("myFile")) {
pw.write("text");
} catch (FileNotFoundException e) {
e.printStackTrace();
}
With BufferedWriter you can just write the strings, arrays or characters data directly to the file:
void makeDirectory() throws IOException {
// Creates Directory
File mydir = new File("MyDir");
mydir.mkdir();
// Creates new file object
File myfile = new File("MyDir", "Anyfile.txt");
//Create actual file Anyfile.txt inside the directory
BufferedWriter bw = new BufferedWriter(new FileWriter(myfile.getAbsoluteFile()));
String str = "This file is created through java";
bw.write(str);
bw.close();
}
I try to put some file fileNamePath in zip archive (arguments are D:\text.txt D:\archive.zip):
public static void main(String[] args) throws IOException {
if (args.length==0) return;
String fileNamePath = args[0];
String zipPath = args[1];
FileOutputStream outputStream = new FileOutputStream(zipPath);
ZipOutputStream zipOutputStream = new ZipOutputStream(outputStream);
zipOutputStream.putNextEntry(new ZipEntry(fileNamePath));
File file = new File(fileNamePath);
Files.copy(file.toPath(),zipOutputStream);
zipOutputStream.closeEntry();
zipOutputStream.close();
}
Archive is created but i don't see any file in it. Why?
That code is working perfectly:
zip.java
import java.io.*;
import java.nio.file.*;
import java.util.zip.*;
public class zip
{
public static void main(String[] args) throws IOException {
if (args.length==0) return;
String fileNamePath = args[0];
String zipPath = args[1];
FileOutputStream outputStream = new FileOutputStream(zipPath);
ZipOutputStream zipOutputStream = new ZipOutputStream(outputStream);
zipOutputStream.putNextEntry(new ZipEntry(fileNamePath));
File file = new File(fileNamePath);
Files.copy(file.toPath(),zipOutputStream);
zipOutputStream.closeEntry();
zipOutputStream.close();
}
}
I have compiled it under Debian 9 Stretch, OpenJDK 8
I have then created a sample txt file:
hello.txt
Hello World
I then compiled it:
javac zip.java
And finally run it:
java zip hello.txt hello.zip
I extract the .zip and open up hello.txt, returning Hello World
May it be that you have no permissions to read/write D:\?
I have a following save method, but I dont know how to verify that the method is working correctly. How can I verify it in Test Class ??
static void saveFile(List<String> contents, String path){
File file = new File(path);
PrintWriter pw = new PrintWriter(new BufferedWriter(new FileWriter(file)));
for(String data : contents){
pw.println(data);
}
}
Sorry, contents is not String, but List. But is there no need to make test class ?? because it is constructed by tested java method.
For testing, you may consider a test framework such as jUnit and write your test case. In your specific case, you could write something as follows:
public class TestCase {
#Test
public void test() throws IOException {
String contents = "the your content";
String path = "the your path";
// call teh metod
saveFile(contents, path);
// tacke a reference to the file
File file = new File(path);
// I assert that the file is not empty
Assert.assertTrue(file.length() > 0);
// I assert that the file content is the same of the contents variable
Assert.assertSame(Files.readLines(file, Charset.defaultCharset()).stream().reduce("", (s , s2) -> s+s2),contents);
}
static void saveFile(String contents, String path) throws IOException {
File file = new File(path);
PrintWriter pw = new PrintWriter(new BufferedWriter(new FileWriter(file)));
pw.println(contents);
}
}
In this way, you have a framework to check if the your code works as you expect. If this isn't sufficient, you should look into a mock framework such as Mockito.
Remove FileWriter from you method like this
static void saveFile(List<String> contents, Writer writer){
PrintWriter pw = new PrintWriter(new BufferedWriter(writer));
for(String data : contents){
pw.println(data);
}
pw.flush();
}
In your JUnit test method use StringWriter for checking your saving logic
#Test
void testWriter() {
StringWriter writer = new StringWriter();
saveFile(Arrays.asList("test content", "test content2"), writer);
assertEquals("test content\ntest content2\n", writer.toString());
}
and in your real code
...
Writer writer = new FileWriter(new File(path));
saveFile(Arrays.asList("real content", "real content2"), writer);
...
I'm trying to read a .xlsx file from the project folder using the following code, but it always throws FileNotFoundException. I have attached the project structure where the file is.
public static void main(String[] args) {
try {
String excelFilePath = "‪DataModel.xlsx";
File file = new File(excelFilePath);
FileInputStream fis = new FileInputStream(file);
} catch (Exception ex) {
System.out.print(ex);
}
}
This is how I normally would approach it:
File file = new File( javaApplication2.class.getResource( excelFilePath ).getPath() );
classLoader.getResource() solved the problem
I have a program that is suppose to read all the files in my folder and combine the files into on file and place them into a new folder. Some of the files are not being pulled in and I do not know why.
The file names are wonder1.txt, wonder2.txt, wonder3.txt, and wonder4.txt and the folder name is Alice, but only a few of the files are actually in the new folder.
import java.io.*;
import java.util.Scanner;
import java.util.*;
import java.lang.*;
import java.io.PrintWriter;
public class alice {
public static void main(String[] args) throws FileNotFoundException, IOException {
File folder = new File("/Users/DAndre/Desktop/Alice");
//Reads in all the files in that folder
for (final File fileEntry : folder.listFiles()) {
String fileName = fileEntry.getAbsolutePath();
BufferedReader br = new BufferedReader(new FileReader(fileName));
try {
StringBuilder stringBuilder = new StringBuilder();
String line = br.readLine();
while (line != null) {
stringBuilder.append(line);
stringBuilder.append("\n");
line = br.readLine();
}
/**
* Pass original file content as string to another method which
* creates new file with same content.
*/
newFile(stringBuilder.toString());
} finally {
br.close();
}
}
}
public static void newFile(String fileContent) {
try {
String newFileLocation = "/Users/DAndre/Desktop/final/final_copy.txt";
PrintWriter writer = new PrintWriter(newFileLocation);
writer.write(fileContent);//Writes original file content into new file
writer.close();
System.out.println("File Created");
} catch (Exception e) {
e.printStackTrace();
}
}
}
The problem with your solution is that you haven't initialize PrintWriter in append mode, because of which the new file gets overwritten with the content of the last file that was written.
public static void newFile(String fileContent) {
try {
String newFileLocation = "C:\\Users\\Shayan\\Desktop\\files2\\final_copy.txt";
PrintWriter writer = new PrintWriter(new FileOutputStream(new File(newFileLocation), true /* append = true */));
writer.write(fileContent);//Writes original file content into new file
writer.close();
System.out.println("File Created");
} catch (Exception e) {
e.printStackTrace();
}
}
The last argument in the constructor of FileOututStream is set to true, indicating that it should be opened in append mode.
You need to change
PrintWriter writer = new PrintWriter(newFileLocation);
to
PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(newFileLocation, true)))
Little explanation: append meant to write it additively, on the contrary write overrides the existing file. In your code you are creating a new file including one of your wonders, but on next iteration the file is recreated. So the content of previous wonder is gone.
With the change PrintWriter object is not recreating the file, instead it writes content to a BufferedWriter which also transfers the stream to an append able FileWriter object.
Little suggest: do not create a PrintWriter object on each iteration.
Second little suggest: You don't need PrintWriter. BufferedWriter itself is good enough as far as I see.