hello i am a newbie to java. i just started learning java last week.
below is a code I am using to display all files and the corresponding file sizes of a folder and it's subfolder.
However, instead of displaying the output in the Eclipse console, what I need to achieve is actually output the same data to a text file. I've been searching on the net on how to accomplish this over the last couple of days but I wasn't able to come to a solution.
Can someone advise me on what code to use to accomplish my task?
Thanks so much!
public class ReadFile1 {
public static void main(String[] a)throws IOException{
showDir(1, new File("/Users/User/Documents/1 eclipse test/testfolder1"));
//File file = new File("/Users/User/Documents/1 eclipse test/testfolder1/puppy4.txt");
//long fileSize = file.length();
}
static void showDir(int indent, File file) throws IOException {
for (int i = 0; i < indent; i++)
System.out.print('-');
System.out.println(file.getName() + " - " + file.length() / 1024 + " KB");
if (file.isDirectory()) {
File[] files = file.listFiles();
for (int i = 0; i < files.length; i++)
showDir(indent + 4, files[i]);
}
}
}
Here is your example converted :
public class ReadFile1
{
public static void main(String[] a) throws IOException
{
FileWriter fstream = new FileWriter("C:\\test.txt",true);
BufferedWriter out = new BufferedWriter(fstream);
showDir(out,1,new File("C:\\"));
out.flush();
out.close();
}
static void showDir(BufferedWriter writer, int indent, File file) throws IOException
{
for(int i = 0; i < indent; i++)
{
writer.write('-');
//System.out.print('-');
}
writer.write(file.getName() + " - " + file.length() / 1024 + " KB");
writer.newLine();
//System.out.println(file.getName() + " - " + file.length() / 1024 + " KB");
if(file.isDirectory())
{
File[] files = file.listFiles();
for(int i = 0; i < files.length; i++)
{
showDir(writer,indent + 4, files[i]);
}
}
}
}
Update your showDir with the file writing code as mentioned here:
File file = new File("info.txt");
// if file doesnt exists, then create it
if (!file.exists()) {
file.createNewFile();
}
PrintWriter writer = new PrintWriter(file);
writer.println(file.getName() + " - " + file.length() / 1024 + " KB");
writer.close();
This will put the console output into the text file:
try{
PrintStream out = new PrintStream(new FileOutputStream("output.txt"));
System.setOut(out);
}catch(SecurityException se){
//Exception handling
}
setOut(PrintStream out) reassigns the "standard" output stream.It throws SecurityException -- if a security manager exists and its checkPermission method doesn't allow reassigning of the standard output stream.
Related
I am trying to delete a json file I just created, The file is in the same directory as the workplace so I didn't include it when creating the new File object.
I also closed the output stream before trying to delete the file by using .close() method.
import java.io.File;
public static void processFilesForValidation(String name, Scanner obj, PrintWriter logFile) {
int count = 0;
PrintWriter outputStream = null;
String[] line = obj.nextLine().split(",", -1);
if (count == 0) {
for (int i = 0; i < line.length; i++) {
try {
if (line[i].equals(" ")) {
throw new CSVFileInvalidException();
} else {
try {
outputStream = new PrintWriter((new FileOutputStream(name + ".json", true)));
} catch (FileNotFoundException e) {
System.out.println("Could not create json file " + name
+ ". Program will terminate after deleting any corrupted files and closing any opened files.");
obj.close();
outputStream.close();
String fname = name + ".json";
File file = new File(fname);
file.delete();
System.exit(0);
}
}
} catch (CSVFileInvalidException eCsvFileInvalidException) {
System.out.println(
"File " + name + ".CSV is invlaid: field is missing. \nFile is not converted to JSON.");
int detected = line.length - 1;
logFile.println("\nFile " + name + ".CSV is invalid. \nMissing field:" + detected
+ " detected, 1 missing");
for (int j = 0; j < line.length; j++) {
if (line[j].equals(" ")) {
logFile.print(line[j] + "***, ");
} else {
logFile.print(line[j] + ", ");
}
}
logFile.close();
outputStream.close();
String fname= name+".JSON";
File file = new File(fname);
file.delete();
break;
}
}
}
}
The code is a little long but this is the method, I hope you can help me.
You open a new outputStream every time around the loop. As far as I can tell, you only close it on a couple of errors. So, on loop #2, the first outputStream is left dangling and not closed.
I am trying to make a program, which reads the name of a directory as a command line argument and for each file inside the directory prints the following information: name, length and last modification time.
But doesnt work, only shows length of the same files all the time
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
public class x2 {
static void show(String str) {
System.out.println(str);
}
public static void main(String[] args) {
// TODO Auto-generated method stub
try {
File file = new File(args[0]);
//Here we check whether the given argument is a directory
if(file.isDirectory()) {
System.out.println("Contents of: " + args[0]);
//Here we initialize array con with the content of the
//directory
String dirContent[] = file.list();
// date field ??
Date date = new Date(file.lastModified());
SimpleDateFormat sdf=new SimpleDateFormat("dd:MM:yyyy kk:mm:ss");
//Here we go through the content of the directory one by one
for(int i=0; i<dirContent.length; i++) {
//Here we create an object of class File with the ith
//member of array con
File auxf = new File(args[0] + "/" + dirContent[i]);
//Here we check whether each content is a directory
if(auxf.isDirectory()) {
//Here we initialize array newCon with the content of
//each sub-directory
String newCon[] = auxf.list();
// file lenght ????
long length = file.length();
//Here we check whether the sub-directory is empty or not
if(newCon.length>0){
System.out.println("Content of "+args[0] +"\\"+ dirContent[i]+"\\");
for(int j=0; j<newCon.length; j++)
System.out.println(args[0] +"\\"+ dirContent[i] + "\\" + newCon[j]+" file length:"
+ length +sdf.format(date) );
}
else
System.out.println(dirContent[i] + " is an empty directory.");
} else
System.out.println(dirContent[i] + " is a file.");
}
}
else
System.out.println(args[0] + " is a file.");
}catch(Exception e) {
System.out.println("Usage: java showDir file_or_dir_name");
}
}
}
Can someone help me fix the code.
You are actually calling file.length() on the root directory :
public static void main(String[] args) {
try {
File file = new File(path);
[...]
for(int i=0; i<dirContent.length; i++) {
File auxf = new File(path + "/" + aDirContent);
[...]
//Maybe you meant auxf.length() ?
long length = file.length();
I'm programming a conversion tool that should take a json file as an input. Due to the problem that json input files may be very large I'll perform a split at the beginning. I have to resort the structure of the input file and because I don't want to keep the whole large file in my memory all the time, I'll split it.
I'm proofing the occurences of a json block by counting the { and }. If the counter is 0, a split should be performed. That's where the problem is: if the file is about 40MBs large the JVM throws a StackOverFlowError and I don't know why.
Here's what I do to perform a split:
/*
* Utility-function to read a json file part by part and save the parts to a separate json file.
* #param scanner The scanner which contains the file and which returns the lines from the file.
* #param j The counter of the file. As the file should change whenever the counter changes.
* #return jsonString The content of the jsonString.
*/
public String readPartOfFileAndSave(String filepath, Scanner scanner, int j) {
String jsonString = "";
int i = 0;
++j;
while (scanner.hasNext()) {
String token = scanner.next();
jsonString += token + System.lineSeparator();
if (token.contains("{")) {
i++;
}
if (token.contains("}")) {
i--;
}
if (i == 0) {
// DEBUG
// if (j % 1000 == 0) {
// System.gc();
// System.out.println("Garbage Collector called manually");
// }
saveFile(filepath, "actor", j, jsonString);
readPartOfFileAndSave(filepath, scanner, j);
}
}
return "";
}
/*
* #param filename The name of the target file where the content is saved to.
* #param j The counter of the file. As the file should change whenever the counter changes.
* #param content The content of the file.
*/
public void saveFile(String filepath, String fileprefix, int j, String content) {
File file = null;
if (this.osValidator.isWindows()) {
file = new File(filepath + "\\" + fileprefix + "" + j + ".json");
} else {
file = new File(filepath + "/" + fileprefix + "" + j + ".json");
}
try {
// if file doesnt exists, then create it
if (!file.exists()) {
file.createNewFile();
}
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file.getAbsoluteFile()), "UTF-8"));
bw.write(content);
bw.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
The exception looks like this:
Exception in thread "AWT-EventQueue-0" java.lang.StackOverflowError
at java.util.Hashtable.get(Hashtable.java:363)
at java.util.Properties.getProperty(Properties.java:969)
at java.lang.System.getProperty(System.java:717)
at sun.security.action.GetPropertyAction.run(GetPropertyAction.java:84)
at sun.security.action.GetPropertyAction.run(GetPropertyAction.java:49)
at java.security.AccessController.doPrivileged(Native Method)
at java.io.BufferedWriter.<init>(BufferedWriter.java:109)
at java.io.BufferedWriter.<init>(BufferedWriter.java:88)
at utility.ReadFileAndSave.saveFile(ReadFileAndSave.java:183)
at utility.ReadFileAndSave.readPartOfFileAndSave(ReadFileAndSave.java:158)
at utility.ReadFileAndSave.readPartOfFileAndSave(ReadFileAndSave.java:159)
splitFile() is called in a separate class. But nothing else happens there.
public void splitFile() {
try {
ReadFileAndSave reader = new ReadFileAndSave();
String jsonFilePath = this.converterView.sourceTextField.getText();
File jsonFile = new File(jsonFilePath);
Scanner scanner = new Scanner(new FileInputStream(jsonFile), "UTF-8");
int j = 0;
File newDir = null;
if (this.osValidator.isWindows()) {
newDir = new File(System.getProperty("user.home") + "\\temp\\");
} else {
newDir = new File(System.getProperty("user.home") + "/temp/");
}
if (!newDir.exists()) {
newDir.mkdir();
}
if (this.osValidator.isWindows()) {
reader.readPartOfFileAndSave(System.getProperty("user.home") + "\\temp\\", scanner, j);
} else {
reader.readPartOfFileAndSave(System.getProperty("user.home") + "/temp/", scanner, j);
}
} catch (FileNotFoundException ex) {
Logger.getLogger(FilterController.class.getName()).log(Level.SEVERE, null, ex);
}
}
The input file has about 38.000 blocks in it. About 5.200 will be splitted to separate files. Then the exception is thrown.
The JVM seems to have a problem with the BufferedWriter. Does anyone know how to fix this issue?
I am trying to have my program save, but whenever I try to save a program that exists (so the second run through) it creates the temp, but it does not overwrite the old file.
Here is the code. Can anyone find out why it does not overwrite the old file with the new?
public static void saveBallotData(int i)throws IOException{
PrintWriter outputFile;
outputFile = new PrintWriter("temp2.txt");
File tempCheck = new File (list.get(i).getBallotNumber()+".txt");
if(tempCheck.exists()){
Scanner inputFile = new Scanner(tempCheck);
for(int m = 0; m < list.get(i).getNumberOfChoices(); m++){
if(list.get(i).getVote().equals(list.get(i).getChoice(m))){
//outputFile.println(list.get(i).getChoice(m) + ":" + getInt(m, tempCheck) + 1);
inputFile.nextLine();
}
else{
outputFile.println(inputFile.nextLine());
}
}
}
else{
for(int a = 0; a < list.get(i).getNumberOfChoices(); a++){
if(list.get(i).getVote().equals(list.get(i).getChoice(a))){
outputFile.println(list.get(i).getChoice(a) + ":" + "1");
}
else{
outputFile.println(list.get(i).getChoice(a) + ":" + "0");
}
}
}
System.out.println("PHE");
outputFile.close();
File g = new File("temp2.txt");
File f = tempCheck;
f.delete();
g.renameTo(f);
}
I have this code:
private static void saveMetricsToCSV(String fileName, double[] metrics) {
try {
FileWriter fWriter = new FileWriter(
System.getProperty("user.dir") + "\\output\\" +
fileTimestamp + "_" + fileDBSize + "-" + fileName + ".csv"
);
BufferedWriter csvFile = new BufferedWriter(fWriter);
for(int i = 0; i < 4; i++) {
for(int j = 0; j < 5; j++) {
csvFile.write(String.format("%,10f;", metrics[i+j]));
}
csvFile.write(System.getProperty("line.separator"));
}
csvFile.close();
} catch(IOException e) {
System.out.println(e.getMessage());
}
}
But I get this error:
C:\Users\Nazgulled\Documents\Workspace\Só
Amigos\output\1274715228419_5000-List-ImportDatabase.csv
(The system cannot find the path
specified)
Any idea why?
I'm using NetBeans on Windows 7 if it matters...
In general, a non existent file will be created by Java only if the parent directory exists.
You should check/create the directory tree:
String filenameFullNoPath = fileTimestamp + "_" + fileDBSize + "-"
+ fileName + ".csv";
File myFile = new File(System.getProperty("user.dir") + File.separator
+ "output" + File.separator + filenameFullNoPath);
File parentDir = myFile.getParentFile();
if(! parentDir.exists())
parentDir.mkdirs(); // create parent dir and ancestors if necessary
// FileWriter does not allow to specify charset, better use this:
Writer w = new OutputStreamWriter(new FileOutputStream(myFile),charset);
You can use getParentFile (Java Doc) to make sure that the parent directory exists. The following will check that the parent directory exists, and create it if it doesn't.
File myFile = new File(fileName);
if(!myFile.getParentFile.exists()) {
myFile.getParentFile.mkdirs();
}
I'd guess that the "output" directory doesn't exist. Try adding:
new File(System.getProperty("user.dir") + File.separator + "output").mkdir();