I'm trying to write some text to an html file as an output using PrintWriter, and the text isn't saving to the file.
import java.util.Random;
import java.util.*;
import java.io.PrintWriter;
import java.io.File;
import java.io.FileNotFoundException;
public class Creator
{
static ArrayList<Character> grid = new ArrayList<Character>();
public static void main(String[]args) throws FileNotFoundException
{
char[] alphabet={'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'};
for(int row=0;row<625;row++)
{
grid.add(alphabet[RandGen(0,25)]);
//System.out.print(grid.get(out));
}
Creator.Output();
System.out.println("Executed.");
}
public static int RandGen(int min, int max)
{
Random ran = new Random();
int randomNum = ran.nextInt(max) + min;
return randomNum;
}
public static void Output()throws FileNotFoundException
{
//File file=new File("wsm.html");
//File.createNewFile();
PrintWriter writer = new PrintWriter("wordsearchmaker.html");
writer.println("<html>");
writer.println("<table>");
writer.println("tr");
for(int j=0;j<25;j++)
{
//for(int k=0;k<25;k++)
// {
System.out.println("<th>"+grid.get(j));
writer.println("<th>"+grid.get(j));
// }
}
writer.flush();
writer.close();
System.out.println("Outputting...");
}
}
So I've checked that the methods are all running (hence the "outputting..."), and I system.out.printed the content that I'm intending to write to the file, which is outputting exactly what I want it to. It's supposed to output html code into a html file (named wordsearchmaker.html), but nothing is saving to the file. Everywhere I looked online just said to make sure I'm closing the writer, which I did.
Note: I am working in eclipse, which has always been kind of finicky with me, so I may be messing something up there? I don't usually work in eclipse so that's totally possible.
It looks like you've opened the PrintWriter, which enables you to send data to the file. But you haven't actually opened or created a file.
Try first creating a new file and modifying it:
import java.io.File;
File newFile = new File ("LOCATION OF FILE");
Then, set your PrintWriter to use newFile.
Related
I've written some java code that creates a CSV file at the mount point of a disk I have attached to a Google Compute instance. I run the script in the form of a SQL stored procedure from the instance that the disk is attached to. The issue is that at the mount point, a "lost+found" folder is created where I would expect to find my CSV file. What am I doing wrong? Thank you for your time! The code is similar to as follows:
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.FileOutputStream;
public class file_write {
public static void main(String[] args) throws IOException{
String filePath = "/mnt/point/file.csv";
// Creates file in mount point
File myFile = new File(filePath);
myFile.getParentFile().mkdirs();
myFile.createNewFile();
FileWriter stringWriter = new FileWriter(myFile);
for(int i = 0; i < 100000; i++) {
stringWriter.write(i + ", ");
stringWriter.write("something");
stringWriter.write(System.lineSeparator());
}
stringWriter.close();
}
}
Im using jxl to store data entered in by the user into an excel spreadsheet. I want to be able to close my program while its running and open up the excel spreadsheet and view the data. Whenever I do this, I get a message that says that it is in a different format than specified in the file extension. Here is my code.
import java.io.File;
import java.io.IOException;
import java.util.Scanner;
import jxl.*;
import jxl.write.*;
import jxl.Workbook;
import jxl.read.biff.BiffException;
import jxl.write.Label;
import jxl.write.Number;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import jxl.write.WriteException;
import jxl.write.biff.RowsExceededException;
public class ReadWriteTest
{
public static void main(String[] args) throws BiffException, IOException, RowsExceededException, WriteException
{
Scanner scan = new Scanner(System.in);
int i = 1;
Integer iAlliance = -1;
File test = new File("C:\\test.xls");
WritableWorkbook wb = Workbook.createWorkbook(test);
while(iAlliance != 0 && i != 5)
{
WritableSheet sheet = wb.createSheet("Sheet" + i, i);
iAlliance = scan.nextInt();
WriteExcel.addNumber(sheet, 0, 0, iAlliance);
iAlliance = scan.nextInt();
WriteExcel.addNumber(sheet, 1, 0, iAlliance);
i++;
}
wb.write();
wb.close();
}
}
"close my program while its running"
Your code needs to handle that. Right now, it just gets killed at any point (probably in that loop), and nothing after that point happens. The WriteableWorkbook never gets write() or close() called, and the file is probably corrupted.
So see this, try adding some simple output at various places, like "got to line number XXX". Run it, close it, and see how far it got.
You'll probably need to wrap the bulk of your code in a try-catch-finally. The loop is inside the try, the catch handles the lightning-out-of-the-blue program closing from that pesky human at the keyboard, and the finally closes up the workbook file properly.
Using some answers from this site I created a small Folder Monitor app in Java. It is supposed to check for changes to a specific folder and output those changes to a text file. Unfortunately it prints the report twice for every change. The problem is I cannot figure out where the first line of the report comes from. Please help me understand what am I doing wrong.
Please find the code below. I removed part of the code as it does not affect the Q&A.
import java.io.File;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.apache.commons.io.monitor.FileAlterationListener;
import org.apache.commons.io.monitor.FileAlterationListenerAdaptor;
import org.apache.commons.io.monitor.FileAlterationMonitor;
import org.apache.commons.io.monitor.FileAlterationObserver;
public class FolderMonitor {
public FolderMonitor() {}
//path to a folder you are monitoring
public static final String FOLDER = "D:\\WatchedDir";
public static void main(String[] args) throws Exception
{
System.out.println("monitoring started");
// The monitor will perform polling on the folder every 5 seconds
final long pollingInterval = 6 * 1000;
// Let's get a directory as a File object and sort all its files.
File folderToMonitor = new File(FOLDER);
File outputFile = new File("H:\\Dir_changes.txt");
if (!folderToMonitor.exists())
{
// Test to see if monitored folder exists
throw new RuntimeException("Directory not found: " + FOLDER);
}
FileAlterationObserver observer = new FileAlterationObserver(folderToMonitor);
FileAlterationMonitor monitor = new FileAlterationMonitor(pollingInterval);
FileAlterationListener listener = new FileAlterationListenerAdaptor()
{
// Is triggered when a file in the monitored folder is modified from
#Override
public void onFileChange(File file)
{
// "file" is the reference to the newly created file
try {writeToFile(outputFile, convertLongToDate(outputFile.lastModified()), ("File modified: "+ file.getCanonicalPath()));}
catch (IOException e) {e.printStackTrace();}
}
};
observer.addListener(listener);
monitor.addObserver(observer);
monitor.start();
}
private static void writeToFile(File filePath, String timeStamp, String caughtChange) throws IOException
{
FileWriter fileWriter = new FileWriter(filePath,true);
BufferedWriter bufferFileWriter = new BufferedWriter(fileWriter);
fileWriter.append("\r" + timeStamp + " - " + caughtChange + "\r");
bufferFileWriter.close();
}
private static String convertLongToDate(long input)
{
Date date = new Date(input);
Calendar cal = new GregorianCalendar();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MMM/dd hh:mm:ss z");
sdf.setCalendar(cal);
cal.setTime(date);
return sdf.format(date);
}
}
The output looks like this:
1454622374878 File modified: D:\WatchedDir\second\inside3.txt
2016/Feb/04 04:46:25 EST - File modified: D:\WatchedDir\second\inside3.txt
I can not figure out where the highlighted (bold) part comes from and how to get rid of it. Please help!
I ran the same code that you posted and don't see the extra output in the .txt file. can you please try it by directing the output to a new file and see if it makes any difference
For some reason Eclipse was executing code that I have already removed from the class and saved the changes.
After I have restarted Eclipse and executed the code again, everything was running fine (surprise).
I considered deleting this post but I decided to leave it just in case someone will be looking for such a piece of code. I will leave it to the moderators to decide if this question should be deleted.
I have to move files from one directory to other directory.
Am using property file. So the source and destination path is stored in property file.
Am haivng property reader class also.
In my source directory am having lots of files. One file should move to other directory if its complete the operation.
File size is more than 500MB.
import java.io.File;
import java.nio.file.Files;
import java.nio.file.StandardCopyOption;
import static java.nio.file.StandardCopyOption.*;
public class Main1
{
public static String primarydir="";
public static String secondarydir="";
public static void main(String[] argv)
throws Exception
{
primarydir=PropertyReader.getProperty("primarydir");
System.out.println(primarydir);
secondarydir=PropertyReader.getProperty("secondarydir");
File dir = new File(primarydir);
secondarydir=PropertyReader.getProperty("secondarydir");
String[] children = dir.list();
if (children == null)
{
System.out.println("does not exist or is not a directory");
}
else
{
for (int i = 0; i < children.length; i++)
{
String filename = children[i];
System.out.println(filename);
try
{
File oldFile = new File(primarydir,children[i]);
System.out.println( "Before Moving"+oldFile.getName());
if (oldFile.renameTo(new File(secondarydir+oldFile.getName())))
{
System.out.println("The file was moved successfully to the new folder");
}
else
{
System.out.println("The File was not moved.");
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
System.out.println("ok");
}
}
}
My code is not moving the file into the correct path.
This is my property file
primarydir=C:/Desktop/A
secondarydir=D:/B
enter code here
Files should be in B drive. How to do? Any one can help me..!!
Change this:
oldFile.renameTo(new File(secondarydir+oldFile.getName()))
To this:
oldFile.renameTo(new File(secondarydir, oldFile.getName()))
It's best not to use string concatenation to join path segments, as the proper way to do it may be platform-dependent.
Edit: If you can use JDK 1.7 APIs, you can use Files.move() instead of File.renameTo()
Code - a java method:
/**
* copy by transfer, use this for cross partition copy,
* #param sFile source file,
* #param tFile target file,
* #throws IOException
*/
public static void copyByTransfer(File sFile, File tFile) throws IOException {
FileInputStream fInput = new FileInputStream(sFile);
FileOutputStream fOutput = new FileOutputStream(tFile);
FileChannel fReadChannel = fInput.getChannel();
FileChannel fWriteChannel = fOutput.getChannel();
fReadChannel.transferTo(0, fReadChannel.size(), fWriteChannel);
fReadChannel.close();
fWriteChannel.close();
fInput.close();
fOutput.close();
}
The method use nio, it make use os underling operation to improve performance.
Here is the import code:
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
If you are in eclipse, just use ctrl + shift + o.
I've tried directly linking using the entire path but that hasn't solved it either.
package eliza;
import java.io.*;
public class Eliza {
public static void main(String[] args) throws IOException {
String inputDatabase = "src/eliza/inputDataBase.txt";
String outputDatabase = "src/eliza/outputDataBase.txt";
Reader database = new Reader();
String[][] inputDB = database.Reader(inputDatabase);
String[][] outputDB = database.Reader(outputDatabase);
}
}
Here is the reader class:
package eliza;
import java.io.FileReader;
import java.io.BufferedReader;
import java.io.IOException;
public class Reader {
public String[][] Reader(String name) throws IOException {
int length = 0;
String sizeLine;
FileReader sizeReader = new FileReader(name);
BufferedReader sizeBuffer = new BufferedReader(sizeReader);
while((sizeLine = sizeBuffer.readLine()) != null) {
length++;
}
String[][] database = new String[length][1];
return (database);
}
}
Here's a photo of my directory. I even put these text files in the "eliza" root folder: here
Any ideas?
Since you are using an IDE, you need to give the complete canonical path. It should be
String inputDatabase = "C:\\Users\\Tommy\\Desktop\\Eliza\\src\\eliza\\inputDataBase.txt";
String outputDatabase = "C:\\Users\\Tommy\\Desktop\\Eliza\\src\\eliza\\outputDataBase.txt";
The IDE is probably executing the bytecode from its bin folder and cannot find the relative reference.
give the exact path like
String inputDatabase = "c:/java/src/eliza/inputDataBase.txt";
you have not given the correct path, Please re check
try
{BASE_PATH}+ "Eliza/src/inputDataBase.txt"
The source directory tree isn't generally present during execution, so files that are required at runtime shouldn't be put there ... unless you're going to use them as resources, in which case their pathname is relative to the package root, and does not begin with 'src', and the data is accessed by a getResourceXXX() method, not via a FileInputStream.