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();
}
Related
I'm writing and reading from a file and it works perfectly fine. However when the activity is switched or the app is closed it appears that the file is deleted or some such as null is returned when trying to read from the file. I believed it may be because I have an onCreate blank write to the file but that should only run upon the launch to make sure the file is created. I don't mind if the file doesn't persist between launches however it should at least persist between activities.
//in oncreate is writeToHistory("");
public void writeToHistory(String toWrite) {
try {
File path = getApplicationContext().getFilesDir();
File file = new File(path, "JWCalcHistory.txt");
FileOutputStream fos = new FileOutputStream(file);
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(fos));
bw.write(toWrite);
bw.close();
} catch (Exception e){
e.printStackTrace();
}
}
public void btnAnsClicked(View v) throws IOException {
File path = getApplicationContext().getFilesDir();
File file = new File(path,"JWCalcHistory.txt");
BufferedReader br = new BufferedReader(new FileReader(file));
String oldAns = br.readLine();
if (!(oldAns.equals("null") || oldAns.equals(""))) {
if (Character.isDigit(readableSum.charAt(readableSum.length() - 1))) {
oldAns = "*" + oldAns;
}
UpdateSum(oldAns);
}
}
If someone can point out a way to make the contents of the file persist always until it is programmatically deleted or cleared then please let me know. The file doesn't already exist and is created upon the code being run.
You need to check if the file exists first. Something like this:
public void writeToHistory(String toWrite) {
try {
File path = getApplicationContext().getFilesDir();
File file = new File(path, "JWCalcHistory.txt");
if(file.exists()) return;
FileOutputStream fos = new FileOutputStream(file);
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(fos));
bw.write(toWrite);
bw.close();
} catch (Exception e){
e.printStackTrace();
}
}
I'm trying to read a file in java, when I run the program through the IDE it works fine but when it tries to open it when I execute the jar it says the file does not exist. Here is the code where it fails.
public class Main {
public static void main(String[] args) {
try {
App app = new App("files/" + "jsonFile.json", printWriter);
app.runApp();
} catch (Exception e) {
logger.error("error", e);
}
}
}
public class App {
public void runApp(){
File fileDescription = new File("./" + pathDescription);
StringBuilder allDescription = new StringBuilder();
try {
FileReader fr = new FileReader(fileDescription);
BufferedReader br = new BufferedReader(fr);
String line = "";
while ((line = br.readLine()) != null) {
allDescription.append(line);
}
JSONDescription = allDescription.toString();
fr.close();
br.close();
} catch (IOException e) {
logger.error("Error reading file",e);
}
}
}
I know the file exists inside the jar because I looked manually into the jar using jarzilla. Any idea of what it could be happening.
You can lookup a file inside a jar using something like this:
InputStream stream = ClassInsideTheJar.class.getResourceAsStream("/files/jsonFile.json");
BufferedReader br = new BufferedReader(new InputStreamReader(stream));
Where "ClassInsideTheJar" is any class in the jar.
To access files within the JAR, you could use something like
BufferedReader reader = new BufferedReader(new InputStreamReader(
this.getClass().getResourceAsStream("files/jsonFile.json")));
This assumes that there is a folder called files in the root of your jar, and inside that you have the jsonFile.json file.
When you run the program inside an IDE, the compiled code exists outside the jar, in the file system. The IDE compile the code, and then run the program, without building the JAR file. So, your program found the file, because that file still exists in the file system.
To open a file inside a JAR, you need to use another API: loading the file as a resource.
load file within a jar
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 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.
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();
}
}