I'm attempting to create a text (numbers.txt) file where the user indicates that they can save files. I know
File directory = new File("/home/jon/somewhere");
File fullPath = new File(directory, fileName);
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(
(new FileOutputStream(fullPath), charSet));
try {
writer.write("\n");
writer.write("work");
} finally {
writer.close();
}
needs to be inserted, but I don't know how to make it create the .txt file at that location, which is user defined through the scanner. Here's my code so far, up to the point I'm expecting to input the code above. Using Eclipse IDE, if this is information is needed.
The point of the code is to save the numbers to the txt file and pull them back to read them, so they can be calculated.
import java.io.IOException;
import java.nio.file.DirectoryStream;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.Path;
import java.util.Scanner;
import java.io.Serializable;
import java.lang.SecurityException;
import java.util.Formatter;
public class StrangeAverage implements Serializable{
/**
* #param args
*/
public static void main(String[] args) throws IOException
{
// TODO Auto-generated method stub
Scanner input = new Scanner(System.in);
int fails = 0;
do {
System.out.printf("Please enter a directory where you can save files, in case of error/shutdown: ");
Path path = Paths.get(input.nextLine());
if (Files.isDirectory(path))
{
System.out.println("Using Directory " +path);
break;
}
else
{
System.out.println("That's not an open directory.");
fails++;
}
}while(fails < 5);
if (fails == 5)
{
System.out.print("Too many failed attempts. Exiting...");
return;
}
if (fails < 5)
{
System.out.println("Valid Directory.");
}
System.out.printf("Please enter ten integers:");
Create a java.io.FileWriter object first, then create a java.io.PrintWriter based on that FileWriter object. Then you can use PrintWriter.print() to add text to the file:
FileWriter fileWriter = new FileWriter("filename.ext", true);
PrintWriter out = new PrintWriter(fileWriter);
out.print("Text to go in the file");
out.println("Text to go in the file");
Note that you'll need to encase this code in a try-catch block to handle IOExceptions:
try {
FileWriter fileWriter = new FileWriter("filename.ext", true);
PrintWriter out = new PrintWriter(fileWriter);
out.print("Text to go in the file");
out.println("Text to go in the file");
} catch (java.io.IOException e) {
//handle
}
out.close(); //Don't forget to close the file when done
Let's assume that you successfully read the file into the String and the numbers into an array of numbers and the path is an absolute path.
String nameOfTheFile = "/absolute/path";
int[] numbersToStore = new int[]{1,2,3,4,5};
then you will create the .txt file on the location like this:
File txtWithNumbers = new File(nameOfTheFile + ".txt");
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(
new FileOutputStream(txtWithNumbers), charSet
)
);
try {
for(int i in numbersToStore) {
writer.write(i + "\n");
}
} finally {
writer.close();
}
Related
I'm trying to download an xlsx file with reactJS but i'm receiving this message when i try to open my file after download:
"Excel can not open file 'file.xlsx' because the file format or file extension is not valid. Verify that the file has not been corrupted and that the file extension matches the file format"
Here's the frontend code:
const REST_DOWNLOAD_URL = REST_URL + '/token';
Rest.ajaxPromise('GET', REST_DOWNLOAD_URL).then(function (res) {
var FILE_URL = "/supermarket/token/" + res;
Rest.ajaxPromise('GET', FILE_URL).then(function (my_file) {
let blob = new Blob([my_file._body], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8' });
if (navigator.msSaveOrOpenBlob) {
navigator.msSaveBlob(blob, 'file.xlsx');
} else {
let link = document.createElement('a');
link.href = window.URL.createObjectURL(blob);
link.setAttribute('download', 'file.xlsx');
document.body.appendChild(link);
link.download = '';
link.click();
document.body.removeChild(link);
}
});
});
Why am i getting this error? Please somebody help me, i'm stuck on this for 3 weeks
[EDIT 1]
The file that i'm trying to download is build on backend, basically i get the values on database and use the Apache poi workbook to create the excel sheet. I will show you the mainly parts of the code:
1) This method is called by frontend on the first GET requisition of frontend and aims to prepare the file before the download. Is very simple, just create a token (buildToken()) and associate a temp file with this token (createTempFile(randomBackendToken)). The temp file is filled with what i get on my database (createFile(os))
#RequestMapping(value = "/token", method = RequestMethod.GET)
public String returnToken() throws IOException {
String randomBackendToken = tokenGenerator.buildToken();
OutputStream os = tokenGenerator.createTempFile(randomBackendToken);
tokenGenerator.createFile(os);
return randomBackendToken;
}
2) The method where i create the temp file:
public OutputStream createTempFile(String randomBackendToken) throws IOException {
OutputStream os = null;
File file = File.createTempFile(randomBackendToken, ".xlsx");
os = new FileOutputStream(file);
return os;
}
3) The method where i receive the empty temp file and fills with my data on database:
public void createFile(OutputStream os) throws IOException {
List<Supermakets> supermarkets = service.findAllSupermarkets();
Workbook workbook = writeExcel.createSheet(supermarkets);
workbook.write(os);
IOUtils.closeQuietly(os);
}
4) My WriteExcel Class that build the xlsx file:
private static String[] columns = {"Code", "Name", "Type"};
public Workbook createSheet(List<Supermarket> supermarkets) throws IOException {
Workbook workbook = new XSSFWorkbook();
Sheet sheet = workbook.createSheet("file");
[....]
// Row for Header
Row headerRow = sheet.createRow(0);
// Header
for (int col = 0; col < columns.length; col++) {
Cell cell = headerRow.createCell(col);
cell.setCellValue(columns[col]);
cell.setCellStyle(headerCellStyle);
}
//Content
int rowIdx = 1;
for (Supermarket supermarket : supermarkets) {
Row row = sheet.createRow(rowIdx++);
row.createCell(0).setCellValue(supermarket.getCode());
row.createCell(1).setCellValue(supermarket.getName());
row.createCell(2).setCellValue(supermarket.getType());
}
return workbook;
}
So, this all above is just for the first GET requisition. I make another one and the method below holds the second requisition. I just verify the token that the frontend returns for me and them, based on the validation, i allow the download of the file that i created on the previous step:
public void export(#PathVariable(value = "frontendToken") String frontendToken, HttpServletResponse response) throws IOException {
if (StringUtils.isNotBlank(frontendToken)) {
String tmpdir = System.getProperty("java.io.tmpdir");
File folder = new File(tmpdir);
File[] listOfFiles = folder.listFiles();
for (int i = 0; i < listOfFiles.length; i++) {
if (listOfFiles[i].isFile()) {
boolean fileIsValid = tokenGenerator.validateToken(frontendToken, listOfFiles[i]);
if (fileIsValid) {
InputStream input = new FileInputStream(listOfFiles[i]);
OutputStream output = response.getOutputStream();
int data = input.read();
while (data != -1) {
output.write(data);
data = input.read();
}
input.close();
output.flush();
output.close();
String mimeType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
response.setContentType(mimeType);
listOfFiles[i].delete();
}
}
}
}
}
And that's all that i'm doing. Can't find what's wrong or what i'm missing. When i press F12 on my navigator to see the response of the request, shows for me something encoded, like:
PK#SM_rels/.rels’ÁjÃ0†_ÅèÞ8í`ŒQ·—2èmŒî4[ILbËØÚ–½ýÌ.[Kì($}ÿÒv?‡I½Q.ž£uÓ‚¢hÙùØx>=¬î#ÁèpâH"Ã~·}¢
Any suspicions of what can be?
guys!
The problem was: my binary data was being converted for string by javascript and this was breaking my excel file. i solved my problem converting my binary data on backend to text and then on frontend i make the inverse. The following links helped me:
java convert inputStream to base64 string
Creating a Blob from a base64 string in JavaScript
Thank you for everyone that tried to help. I hope my question can help others
I want to retrieve data from a website using Nashorn script engine
I have the java code where I can retrieve data from a sample website template.
Now I want to call that java file from java script file.
following is the code:
JAVA CODE(Nsample.java):
package sample;
import java.net.*;
import java.io.*;
public class Nsample
{
public static void main(String[] args)
{
String output = getUrlContents("https://freewebsitetemplates.com/");
System.out.println(output);
}
public static String getUrlContents(String theUrl)
{
StringBuilder content = new StringBuilder();
try
{
URL url = new URL(theUrl);
URLConnection urlConnection = url.openConnection();
BufferedReader bufferedReader = new BufferedReader(new
InputStreamReader(urlConnection.getInputStream()));
String line;
while ((line = bufferedReader.readLine()) != null)
{
content.append(line + "\n");
}
bufferedReader.close();
}
catch(Exception e)
{
e.printStackTrace();
}
return content.toString();
}
}
JAVASCRIPT code:(sample.js)
var n = Java.type('C.JavaFolder.sample.Nsample');
var result = n.getUrlContents("https://freewebsitetemplates.com/");
print(result);
I'm trying to compile javascript code using command prompt but it is showing CLASSNOTFOUNDEXCEPTION.
The command was jjs sample.js.Im assuming I did some mistake in Java.type() function.
Can anyone solve this?
This line is the problematic line:
var n = Java.type('C.JavaFolder.sample.Nsample');
Java.type accepts fully qualified java type name. Based on your Java code, your package seems to be "sample" and class name is "Nsample". So the fully qualified class name would be "sample.Nsample".
You should compile your Java classes and specify the directory in -classpath option (of jjs tool or your java application if you use javax.script API with nashorn).
Instead of calling Java from JavaScript , I tried to call JavaScript from java and worked well.
I created some functions in JavaScript and invoked those functions from Java code.
Following is the code.Hope this helps.
Test.java:
import javax.script.*;
import java.io.*;
import java.util.*;
public class Test{
public static void main(String[] args) throws Exception{
ScriptEngine engine = new ScriptEngineManager().getEngineByName("Nashorn");
engine.eval(new FileReader("test.js"));
Invocable invoke = (Invocable)engine;
Object res = invoke.invokeFunction("httpGet","https://www.javaworld.com");
System.out.println(res);
}
}
test.js:
var httpGet = function(theUrl){
var con = new java.net.URL(theUrl).openConnection();
con.requestMethod = "GET";
return asResponse(con);
}
function asResponse(con){
var d = read(con.inputStream);
return d;
}
function read(inputStream){
var inReader = new java.io.BufferedReader(new
java.io.InputStreamReader(inputStream));
var inputLine;
var response = new java.lang.StringBuffer();
while ((inputLine = inReader.readLine()) != null) {
response.append(inputLine);
}
inReader.close();
return response.toString();
}
How can show document file in iframe when i get the file name from database?My database table name is File and my viewmodel is MyFileModel.
public ActionResult Create(HttpPostedFileBase file)
{
try
{
if (ModelState.IsValid)
{
db.Files.Add(new File()
{
FileName = Path.GetFileName(file.FileName)
});
db.SaveChanges();
}
}
catch (Exception)
{
var error = "Sorry not save";
}
return Content("");
}
public FileStreamResult GetPDF()
{
var file = db.Files.Single(s => s.Id == 1);
FileStream fs = new FileStream(Server.MapPath(file.FileName), FileMode.Open, FileAccess.Read);
return File(fs, "application/pdf");
//return View(Server.MapPath("~/File/SegmentAdd.txt"));
//return File(fs,"text/plain");
}
<div id="frame">
<iframe src="#Url.Action("GetPDF","Home")" width="900px" height="500px"></iframe>
</div>
`
The answer which I am posting is all on an assumption, I do not have clear picture of your solution.
If you are not saving a physical file try to save it in a folder and then save the name in the DB OR try to save the entire path in the DB.
Method 1 :
If you are saving the file in a folder say File best way is to add a key in the web.config(.config file which is at the root) as follows
<add key="FilePath" value= "~/File/"/>
and then modify your C# code as follows
public FileStreamResult GetPDF()
{
var file = db.Files.Single(s => s.Id == 1);
string fileName = file.FileName;
string filePath = ConfigurationManager.AppSettings["FilePath"] + fileName;
FileStream fs = new FileStream(Server.MapPath(filePath), FileMode.Open, FileAccess.Read);
return File(fs,"text/plain"); // "text/plain" if your file content-type is text file
//return View(Server.MapPath("~/File/SegmentAdd.txt"));
//return File(fs,"text/plain");
}
Method 2 :
If you are saving the entire path then it makes coding much more simpler and you need not change the code you have written, just go ahead with the same.
Hope this would help you.
I think the way the pdf will open is dependent on the browser that the user uses.
You probably need something like: https://pdfobject.com/.
Good luck!
I tried to convert jsp page to save as pdf by using itext.i downloaded itex.jars and included those in to my project.after that what i will do to get result as pdf page?
Check this link..
http://www.pd4ml.com/examples.htm
Example :
public static void main(String[] args) {
try {
PdfViewerStarter jt = new PdfViewerStarter();
jt.doConversion("http://pd4ml.com/sample.htm", "D:/pd4ml.pdf");
} catch (Exception e) {
e.printStackTrace();
}
}
public void doConversion( String url, String outputPath )
throws InvalidParameterException, MalformedURLException, IOException {
File output = new File(outputPath);
java.io.FileOutputStream fos = new java.io.FileOutputStream(output);
PD4ML pd4ml = new PD4ML();
pd4ml.setHtmlWidth(userSpaceWidth);
pd4ml.setPageSize(pd4ml.changePageOrientation(PD4Constants.A4));
pd4ml.setPageInsetsMM(new Insets(topValue, leftValue, bottomValue, rightValue));
pd4ml.useTTF("c:/windows/fonts", true);
pd4ml.render(new URL(url), fos);
fos.close();
if (Desktop.isDesktopSupported()) {
Desktop.getDesktop().open(output);
} else {
System.out.println("Awt Desktop is not supported!");
}
System.out.println( outputPath + "\ndone." );
}
The statement jt.doConversion("http://pd4ml.com/sample.htm", "D:/pd4ml.pdf");
instead of "http://pd4ml.com/sample.htm" i have to pass dynamic page url and if page is converted into pdf format so that pdf file should be in same format.
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import org.xhtmlrenderer.pdf.ITextRenderer;
import com.lowagie.text.DocumentException;
public class GenratePdf {
public static void generatePDF(String inputHtmlPath, String outputPdfPath)
{
try {
String url = new File(inputHtmlPath).toURI().toURL().toString();
System.out.println("URL: " + url);
OutputStream out = new FileOutputStream(outputPdfPath);
//Flying Saucer part
ITextRenderer renderer = new ITextRenderer();
renderer.setDocument(url);
renderer.layout();
renderer.createPDF(out);
out.close();
}
catch (DocumentException | IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void main(String[] args) {
String inputFile = "D:\\mailPages\\pdfTest.jsp";
String outputFile = "D:/mailPages/testpdf.pdf";
generatePDF(inputFile, outputFile);
System.out.println("Done!");
}
}
We are using pd4ml for downloading a content of JSP in PDF form. You can get the jars here.
Keep this code in your JSP after all the imports
<pd4ml:transform
inline="false"
fileName="application.pdf"
screenWidth="815"
pageFormat="A4"
pageOrientation="portrait"
pageInsets="10,10,10,10,points">
You need to send the html contents to a Java servlet/controller and save the xHTML to PDF.
You'll need to use HtmlPipelineContext and XMLWorker
Have a look here:
Converting HTML files to PDF
and here:
http://itextpdf.com/examples/iia.php?id=56
I have written a file to a specified folder. After writing it to the folder I attach that file to mail. After attaching that file to mail, I want to delete that folder.But folder is not geting deleted and it throws the exception as "The process cannot access the file because it is being used by another process"
Here is my code.
public HttpResponseMessage SendChannelPartenersMessage(string Name,string FirmName,string Address, string Email,string Mobile)
{
var httpRequest = HttpContext.Current.Request;
ContactUs contactUs = new ContactUs();
contactUs.Address = Address;
contactUs.Name = Name;
contactUs.FirmName = FirmName;
contactUs.Email = Email;
contactUs.Mobile = Mobile;
try
{
if (httpRequest.Files.Count > 0)
{
contactUs.AttachFileName = WriteAttachedFile(httpRequest, contactUs.Email);
if (ContactUsService.SendChannelPartenersMessage(contactUs))
{
var fileToBeDeleted = contactUs.AttachFileName;
var deleteFile = DeleteAttachedFile(contactUs.AttachFileName);
}
return Request.CreateResponse(HttpStatusCode.OK, contactUs);
}
else
{
return Request.CreateResponse(HttpStatusCode.BadRequest);
}
}
catch (Exception e)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)
{
Content = new StringContent("An error occurred, please try again or contact the administrator."),
ReasonPhrase = "Critical Exception"
});
}
}
private string WriteAttachedFile(HttpRequest httpRequest, string FileName)
{
var postedFile = httpRequest.Files[0];
var directoryPath = System.Configuration.ConfigurationManager.AppSettings["FolderPath"].ToString() + FileName + "\\\\";
var filePath = directoryPath + postedFile.FileName;
Directory.CreateDirectory(directoryPath);
postedFile.SaveAs(filePath);
var Path = filePath.Replace("\\", "/");
return (Path);
}
private bool DeleteAttachedFile(string FileName)
{
if (System.IO.File.Exists(FileName))
{
System.IO.File.Delete(FileName);
}
string[] words = FileName.Split('/');
string directoryPath = words[words.Length - 2];
if (Directory.Exists(directoryPath))
{
Directory.Delete(directoryPath);
}
return (true);
}
That's because the file you sent through the mail is still not being downloaded at the receiver's end. This happens even in sending files through Skype or even copying to USB stick. Make sure the file is downloaded on the receiver's end