Text File Writing Not Working - java

I have been experimenting with writing to text files for output instead of System.out.println(). When I try this, though, nothing seems to be written. What is the issue with my code?
try{
List<String> lines = Arrays.asList("Data Goes Here");
Path file = Paths.get("output.txt");
Files.write(file, lines, Charset.forName("UTF-8"));
}
catch (IOException ex) {
System.out.println("Frick, something broke. Sorry folks, go home.");
}

I just did a small change to your code by passing the path as the resources directory located in the root of my project. I was able to write to the file successfully.
Here is the updated code:
try {
List<String> lines = Arrays.asList("Data Goes Here");
Path file = Paths.get("./resources/test.txt");
Files.write(file, lines, Charset.forName("UTF-8"));
}
catch (IOException ex) {
ex.printStackTrace();
System.out.println("Frick, something broke. Sorry folks, go home.");
}

Related

How can I plus file's info?

I'm making a new game and I wanna make a coins collector to, later, buy things with those coins. I'm using eclipse.
void save() {
try {
PrintWriter out = new PrintWriter("coins.txt");
out.write(Integer.toString(nmonedas));
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
void load() {
StringBuffer texto=new StringBuffer();
try {
int c;
#SuppressWarnings("resource")
FileReader entrada=new FileReader("coins.txt");
while((c=entrada.read())!=-1){
texto.append((char)c);
}
}
catch (IOException ex) {}
labelshow.setText(texto.toString());
}
I have this code but i cant plus the info. NEED HELP PLS
Well, the thing is, I'm doing a game in eclipse and I want you to collect coins and keep them in a file.
They are collected perfectly and stored in the file, but when I start the game again I want them to be collected but they add up with the previous ones
I assume you are referring to appending text to a .TXT file. If so, you can use something like this:
Files.write(Paths.get("Path to text file here"), "Content".getBytes(), StandardOpenOption.APPEND);
I would put the above in a TRY CATCH block. Also look into PrintWriter as this may be more appopriate to what you need it for as it allows you to continuously write to the file.

Java generate and download csv file

I'm trying to generate and download csv file in a Java project that use an old framework called Echo Studio 3, with Tomcat.
here is my code:
List<Object> reportCount = this.getReport(accountId);
ArrayList<String[]> result = new ArrayList<String[]>();
for (Object list: reportCount) {
String[] rowReport = (String[]) list;
result.add(new String[]{String.valueOf(rowReport[0]),String.valueOf(rowReport[1])});
}
File filename = new File("report.csv");
FileWriter fw = new FileWriter(filename);
fw.append("Name");
fw.append(',');
fw.append("Count");
fw.append('\n');
for (String[] ls: result){
fw.append(ls[0].toString());
fw.append(',');
fw.append(ls[1].toString());
fw.append('\n');
}
try {
fw.flush();
fw.close();
} catch (Exception e) {
System.out.println("Error while flushing/closing fileWriter !!!");
e.printStackTrace();
}
When the code is triggered, nothing happens, and i have no error message. when i run the debug mode, the result is filled with data, and the breakpoint pass throw the flush(), and no error, and the client is not getting the generated file, did I miss something?
You're writing the file to the current working directory, which may be something you don't expect if you're running the program in a container like Tomcat.
Given you've seen the program execute the calls, i'd test that hypothesis by changing the file path to an absolute path, to make sure that the code is actually writing correctly. If it does, then it's just a path issue.
You could also add a call to find the current working directory 1.

Saving file to arraylist and writing back to file; Android

I've been trying to open a text file and and save each line as the contents of an arraylist. Once this has been completed I would like to save it back to a file. I have been running into errors for so long and have tried numerous techniques. I found that for some reason, the files themselves are not being created. It may just be a simple error I'm overlooking but if you could provide any help I will be thankful.
Here's the code:
public void addToFile(){
File root = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/appName/savedlocations");
root.mkdirs();
File fileName = new File(root, "locationslatitude.txt");
File fileName2 = new File(root, "locationslongitude.txt");
String file = fileName.toString();
String file2 = fileName2.toString();
String theContent = Double.toString(currLatitude);
String theContent2 = Double.toString(currLongitude);
s = new Scanner(file);
while (s.hasNext()){
fileList.add(s.next());
}
s.close();
fileList.add(theContent);
s2 = new Scanner(file2);
while (s2.hasNext()){
fileList2.add(s2.next());
}
s2.close();
fileList2.add(theContent2);
try {//works for latitude file
FileWriter writer = new FileWriter(file);
for(String str: fileList) {
writer.write(str);
writer.write("\r\n");
}
writer.close();
} catch (java.io.IOException error) {
//do something if an IOException occurs.
Toast.makeText(this, "Cannot Save Back To A File", Toast.LENGTH_LONG).show();
}
//save the arraylist back to its appropriate file
try {//works for longitude file
FileWriter writer = new FileWriter(file2);
for(String str2: fileList2) {
writer.write(str2);
writer.write("\r\n");
}
writer.close();
} catch (java.io.IOException error) {
//do something if an IOException occurs.
Toast.makeText(this, "Cannot Save Back To A File", Toast.LENGTH_LONG).show();
}
}
I believe I found the answer to the problem and I wanted to post it back on here so if anyone else faces the same problem this might help them.
The problem was that it wasn't creating the file. The directory was created using "root.mkdirs();". However, the files were not created and I was trying to read from non-existing files. This is what I believe caused the error. So, in order to fix this problem I altered the code to this:
try{
s = new Scanner(fileName);
while (s.hasNext()){
fileList.add(s.next());
}
s.close();
fileList.add(theContent);
}catch (FileNotFoundException ex){
ex.printStackTrace();
try{
fileName.createNewFile();
}catch (IOException e){
e.printStackTrace();
Toast.makeText(this, "Hit IOException for file one", Toast.LENGTH_SHORT).show();
}
}
try{
s2 = new Scanner(fileName2);
while (s2.hasNext()){
fileList2.add(s2.next());
}
s2.close();
fileList2.add(theContent2);
}catch (FileNotFoundException ex){
ex.printStackTrace();
try{
fileName2.createNewFile();
}catch (IOException e){
e.printStackTrace();
Toast.makeText(this, "Hit IOException for file two", Toast.LENGTH_SHORT).show();
}
}
This was the only piece of code I had to alter. The code which saved back to the file worked. I hope this will be of use to someone and thanks everyone for your help.
This code works in my project. You can use it to save ArrayList contents to text file. Make sure that the directory is created beforehand. Just iterate through your list and use println method to write it to txt file.
FileWriter outFile = new FileWriter(Environment.getExternalStorageDirectory().getAbsolutePath() + "/appName/savedlocations/nameoftextfile.txt");
PrintWriter out = new PrintWriter(outFile);
out.println("PRINT LINES WITH ME");
out.print("NOT NECCESSARILY A NEW LINE");
out.close(); // at the very end
Do not forget to catch IOException.
Have you added the following permission in the AndroidManifest.xml?
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Check if the file directory etc exists on the device in the first place that you are using
/appName/savedlocations Good chance these do not exist. Wrong name for appName or savedLocations. Check this using some file explorer program. Tell us if it exists. Print out the full path name of
Environment.getExternalStorageDirectory().getAbsolutePath() + "/appName/savedlocations
and see if it really exists. Just download an app for file viewing or I think you can connect to the device via eclipse as well. If you need more info on how to do it let us know. But you should first check the actual error message and report this back.
don't invent your own serialization format. java already has that.
ArrayList<String> files = ...; // whatever
// write the object to a file
ObjectOutput out = new ObjectOutputStream(new FileOutputStream("filename.ser"));
out.writeObject(files);
out.close();
// read the object back
InputStream is = new FileInputStream("filename.ser");
ObjectInputStream ois = new ObjectInputStream(is);
ArrayList<String> newFiles = = (ArrayList)ois.readObject();
ois.close();

How to write content to a file

try {
File file = new File("sample.txt");
FileWriter fw = new FileWriter(file,true);
fw.append('d');
fw.write(100);
fw.close();
} catch(IOException exp) {
exp.printStackTrace();
}
I am unable to append or write anything to the file.
But I could read the content from the file.
Is anything wrong with my code?
It sounds like you probably are writing to a file - but not the file you expect to. If no exceptions have been thrown (and swallowing an exception, just writing it to standard out, is rarely the right approach) then the file will exist somewhere.
It will be in whatever directory the code is running from - which may well not be the same as the directory containing the sample.txt file you're reading. I suggest you explore the file system, and also check the Run Configuration in Eclipse to see what the working directory for the app will be.
As an aside, you should be closing the writer in a finally block so that it gets closed even if there's an exception, like this:
File file = new File("sample.txt");
FileWriter fw = null;
try {
fw = new FileWriter(file, true);
fw.append('d');
fw.write(100);
} catch(IOException) {
// Ideally do something to indicate the failure to the caller
// - do you need to catch this at all?
e.printStackTrace();
} finally {
// From Guava
Closeables.closeQuietly(fw);
}
Obviously you can do this without Guava but it'll make things a lot simpler - and not just here. If you're using Java 7 you can make it even simpler with a try-with-resources statement.
http://www.roseindia.net/java/example/java/io/java-write-to-file.shtml
You can Flush context if code is right and still you are facing problem. it "Flushes the stream"
This link can help!
Like was said before the file may be getting cleared out during the build/clean process. Try specificing an absolute path to the file and running it again. Everything you have written is correct sans the corrections already offered.
try {
File file = new File("C:\sample.txt"); // for Windows or possibly just "/sample.txt" for *nix
FileWriter fw = new FileWriter(file,true);
fw.append('d');
fw.write(100);
} catch(IOException e) {
e.printStackTrace();
} finally {
// Good practice to move close to a finally block
fw.close();
}
You may try using the below syntax :
String filename = "C:/sample.txt";
FileWriter fw = new FileWriter(filename,true);

Writing to a File in Java

I'm really new to Java, and I can't write to a file for some reason, my code looks like this:
FileWriter fstream;
try {
fstream = new FileWriter(fileLocation);
BufferedWriter out = new BufferedWriter(fstream);
log.info("test was supposed to be written to the file");
out.write("test");
out.flush();
out.close();
} catch (IOException e) {
log.error("File not created ", e);
}
When I go to the fileLocation, I see my file, but it's empty. My log does say "test was supposed to be written to the file"
What could I be doing wrong here?
Thanks!
UPDATE: My FileLocation variable is a string:
private String fileLocation="/Users/s/out.txt";
I'm using a Mac
Code is fine. Are you checking the right file location? Perhaps you had created the file you're checking before; while your program could be writing elsewhere.

Categories

Resources