Here's a program I've writing in Android Studio to write a CSV file.
I keep receiving the error "Cannot find symbol class".
I need help resolving that.
File fileDir = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "MyDir");
if (!fileDir.exists()) {
try {
fileDir.mkdir();
} catch (Exception e) {
e.printStackTrace();
}
}
File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath()+ File.separator +File.separator+"MyText.txt");
if (!file.exists()) {
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
if (file.exists()) {
try {
FileWriter fileWriter = new FileWriter(file);
BufferedWriter bfWriter = new BufferedWriter(fileWriter);
bfWriter.write("Text Data");
bfWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
}
If that is your complete program it can't compile because each file in Java needs to be a class and you didn't indicate it is a class. And if the class is to be invoked from the command line instead of just instantiated by another class, then you need to name your main entry point.
I've added those things, but have not compiled it. The compiler may generate other errors if the code isn't perfect.
See how that goes and then if you're still stuck update the question with more details and or ask a new more specific question. If this answer helps at all, please give it an up vote.
import java.io.*;
public class WriteCSV
{
public static void main(String args[])
{
File fileDir = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "MyDir");
if (!fileDir.exists()) {
try {
fileDir.mkdir();
} catch (Exception e) {
e.printStackTrace();
}
}
File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath()+ File.separator +File.separator+"MyText.txt");
if (!file.exists()) {
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
if (file.exists()) {
try {
FileWriter fileWriter = new FileWriter(file);
BufferedWriter bfWriter = new BufferedWriter(fileWriter);
bfWriter.write("Text Data");
bfWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
Related
In the code below how come when it say that it has successfully deleted the file, but when I check the file is still there. How would I remove the file. Basically I'm trying the delete the first file that I made after I was done using it to create the second file.
public static void main(String[] args) {
File file = new File("Hello");
try {
file.createNewFile();
} catch (Exception e) { }
try {
PrintWriter e = new PrintWriter(file);
e.println("Hello hi");
e.close();
}catch (Exception e) {}
File file2 = new File("Hello2");
try {
file2.createNewFile();
} catch (Exception e) {}
try {
Scanner x = new Scanner(file);
PrintWriter e = new PrintWriter(file);
while (x.hasNextLine()) {
System.out.println("Hello");}
e.close();
} catch (Exception e) {}
try {
file.delete();
System.out.println("It was deleted");
} catch (Exception e) { }
}
}
file.delete() doesn't throw an IOException, it returns a boolean check into if condition
if(file.delete())
{
System.out.println("File deleted successfully");
}
else
{
System.out.println("Failed to delete the file");
}
using IOUtils.write to write a string to a file
try {
IOUtils.write("test", new FileWriter(configFile));
} catch (Exception e) {
e.printStackTrace();
}
where configfile is the location of the configuration file ("./resources/config.json")
This seems to delete the file and replace it with a file that has no contents.
no exceptions are thrown either.
Make sure to close the stream after use, else the data might not be written to the file.
FileWriter fw=null;
try {
fw= new FileWriter(configFile);
IOUtils.write("test",fw);
}catch (Exception e) {
e.printStackTrace();
}finally
{
IOUtils.closeQuietly(fw);
}
You need to close the writer, or use try with resources. Otherwise everything might not be flushed to disk:
try (FileWriter fw = new FileWriter(configFile)) {
IOUtils.write("test", fw);
} catch (IOException e) {
e.printStackTrace();
}
Try this code:
FileWriter fw = null;
try {
fw = new FileWriter(configFile);
IOUtils.write("test", fw);
} catch (IOException e) {
e.printStackTrace();
} finally {
if(fw != null)
fw.close();
}
I am trying to create 4 index files using FileWriter. However this code throws Concurrent Modification Exception. I searched a few forums and found the use of finally as a solution, which dint work. Please tell me where can the error be.
public synchronized void writeToDisk() throws IndexerException {
// TODO Implement this method
BufferedWriter bw = null;
try {
//System.out.println("entering writeToDisk");
File file = new File("/Users/workspace/master/tmp//Index.txt");
if(IndexAuthor==-1){
file = new File("/Users/workspace/master/tmp/Author.txt");
if (!file.exists()) {
file.createNewFile();
}
}
if(IndexTerm==-1){
file = new File("/Users/workspace/master/tmp/Term.txt");
if (!file.exists()) {
file.createNewFile();
}
}
if(IndexCategory==-1){
file = new File("/Users/workspace/master/tmp/Category.txt");
if (!file.exists()) {
file.createNewFile();
}
}
if(IndexLink==-1){
file = new File("/Users/workspace/master/tmp/Link.txt");
if (!file.exists()) {
file.createNewFile();
}
}
FileWriter fw = new FileWriter(file.getAbsoluteFile(), true);
bw = new BufferedWriter(fw);
bw.write(PostingsList.toString());
//bw.close();
//System.out.println("Done");
} catch (IOException e) {
//do nothing
}
finally
{
try {
if (bw == null)
bw.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
I made a program to produce a file with numbers in it
But the program is not typing any thing in the file it created!
This is the code:
private void OpenMenuActionPerformed(java.awt.event.ActionEvent evt) {
ModFile=new File(NameText.getText() + ".mod");
FileWriter writer = null;
try {
writer = new FileWriter(ModFile);
} catch (IOException ex) {
Logger.getLogger(ModMakerGui.class.getName()).log(Level.SEVERE, null, ex);
}
if(!ModFile.exists()){
try {
ModFile.createNewFile();
System.out.println("Mod file has been created to the current directory");
writer.write(CodesBox.getText());
} catch (IOException ex) {
Logger.getLogger(ModMakerGui.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
When i create a random file, i don't see any thing when i open it!
Please help
Thanks Amir for helping but i noticed i should use FileOutputStream and DataOutputStream...
So, i need help again cause the same problem appeared :(
File ModFile =new File(NameText.getText() + ".mod");
try {
FileOutputStream fos = new FileOutputStream(ModFile);
DataOutputStream dos = new DataOutputStream(fos);
int i = Integer.parseInt(CodesBox.getText());
dos.writeInt(i);
// and other processing
} catch (IOException ex) {
Logger.getLogger(ModMakerGui.class.getName()).log(Level.SEVERE, null, ex);
}finally{
try{
dos.close();
} catch(IOException e) {
e.printStackTrace();
}
}
NetBeans said they cannot find the symbol dos at (dos.close();)
Please help me here again
You have to check that file name is present in NameText.getText().
You dont need to create file, if file dont exist FileWriter will create it self.
You should Close file after processing
private void OpenMenuActionPerformed(java.awt.event.ActionEvent evt) {
//check before file name is nt null
File ModFile =new File("somefile" + ".mod");
FileWriter writer = null;
try {
writer = new FileWriter(ModFile);
writer.write("test..................");
// and other processing
} catch (IOException ex) {
Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
}finally{
try {
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
to use FileOutputStream and write byte array follow the following code
private static void OpenMenuActionPerformed(java.awt.event.ActionEvent evt) {
//check before file name is nt null
File ModFile =new File("somefile" + ".mod");
FileOutputStream writer = null;
String toProcess = "00D0C0DE00D0C0DE F000000000000000";
try {
writer = new FileOutputStream(ModFile);
writer.write(toProcess.getBytes(),0,toProcess.getBytes().length);
} catch (IOException ex) {
Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
}finally{
try {
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
How can I delete the content of a file in Java?
How about this:
new RandomAccessFile(fileName).setLength(0);
new FileOutputStream(file, false).close();
You could do this by opening the file for writing and then truncating its content, the following example uses NIO:
import static java.nio.file.StandardOpenOption.*;
Path file = ...;
OutputStream out = null;
try {
out = new BufferedOutputStream(file.newOutputStream(TRUNCATE_EXISTING));
} catch (IOException x) {
System.err.println(x);
} finally {
if (out != null) {
out.flush();
out.close();
}
}
Another way: truncate just the last 20 bytes of the file:
import java.io.RandomAccessFile;
RandomAccessFile file = null;
try {
file = new RandomAccessFile ("filename.ext","rw");
// truncate 20 last bytes of filename.ext
file.setLength(file.length()-20);
} catch (IOException x) {
System.err.println(x);
} finally {
if (file != null) file.close();
}
May problem is this leaves only the head I think and not the tail?
public static void truncateLogFile(String logFile) {
FileChannel outChan = null;
try {
outChan = new FileOutputStream(logFile, true).getChannel();
}
catch (FileNotFoundException e) {
e.printStackTrace();
System.out.println("Warning Logfile Not Found: " + logFile);
}
try {
outChan.truncate(50);
outChan.close();
}
catch (IOException e) {
e.printStackTrace();
System.out.println("Warning Logfile IO Exception: " + logFile);
}
}
Open the file for writing, and save it. It delete the content of the file.
try {
PrintWriter writer = new PrintWriter(file);
writer.print("");
writer.flush();
writer.close();
}catch (Exception e)
{
}
This code will remove the current contents of 'file' and set the length of file to 0.