copy a string file and change some text - java

I am trying to read a file content, then change some inner text, then copy to a new location.
Running this code under java 1.7., the code creates the file but fail to replace the inside content with the newName.
if (file.isFile()) {
Charset charset = StandardCharsets.UTF_8;
String content = new String(Files.readAllBytes(file.toPath()), charset);
content.replaceAll("(?i)" + oldName, newName);
String newFileName = file.getAbsolutePath().replace(oldName, newName);
File newFile = new File(newFileName);
newFile.getParentFile().mkdirs();
newFile.createNewFile();
Files.write(newFile.toPath(), content.getBytes());
}

The string content won't be changed by the replaceAll function. You have to save it's return value as a new string and use this one.

Can you try with that?
if (file.isFile()) {
Charset charset = StandardCharsets.UTF_8;
String content = new String(Files.readAllBytes(file.toPath()), charset);
content = content.replaceAll("(?i)" + oldName, newName); // Modified here
String newFileName = file.getAbsolutePath().replace(oldName, newName);
File newFile = new File(newFileName);
newFile.getParentFile().mkdirs();
newFile.createNewFile();
Files.write(newFile.toPath(), content.getBytes());
}

Related

While creating a html file in java using file and file writer iam unable to use a title for the html file which contains special characters such as?

String Template="<P>sooper</p>
String InputFolder="D:\\project"
String title="name"
FileWriter myWriter = null;
File htmlContent = new File(InputFolder + File.separator + title+ ".html");
myWriter = new FileWriter(htmlContent);
myWriter.write(Template);
myWriter.close();
This works fine
but when I replace the title with any string which contains special characters the html file is not being created
I was expecting a html file would be created with the name name?.html
You problem is that you try to create a path (under Windows or Linux) with special characters which is not valid for path for your OS. You have to encode the path to the correct one with replasing non ascii symbols to its printable alternative.
public static void main(String... args) throws IOException {
String template = "<p>sooper</p>";
String parent = "d:/project";
String title = "n ame";
File file = new File(parent, encode(title + ".html"));
if (!file.exists()) {
file.getParentFile().mkdirs();
file.createNewFile();
}
try (FileWriter out = new FileWriter(file, true)) {
out.write(template);
}
}
private static String encode(String str) throws UnsupportedEncodingException {
return URLEncoder.encode(str, StandardCharsets.UTF_8.toString());
}
Maybe because there are spaces in your HTML file name. Can you try with Bharatiya_Janta_Party.html or Bharatiya-Janta-Party.html
Please do inform what results did you get.

How to open pdf file in browser

I'm trying to open a pdf file in which has been exported from a repository. Here is the code that I'm using:
ConnectionManager con = new ConnectionManager();
String id = request.getParameter("uname");
String objname = request.getParameter("pass");
Properties prop = new Properties();
//ResourceBundle resource = ResourceBundle.getBundle("query");
//prop.load(getClass().getResourceAsStream("query.properties"));
String uname = "DmAdmin";
String pass = "<pass>";
String docbase = "QDocs";
String ext = new String();
IDfSession ssn = con.getSession(uname, pass, docbase);
sysObj = (IDfSysObject)ssn.getObject((IDfId)new DfId(id));
//ByteArrayInputStream buf = sysObj.getContent();
//sysObj.getFile("C:\\Users\\rsaha04\\Downloads\\"+objname+".pdf");
String path = "C:\\Users\\rsaha04\\Downloads\\";
String filename = path + sysObj.getObjectName().toString();
IDfCollection coll = sysObj.getRenditions(null);
if (coll != null)
{
while (coll.next())
{
String format = coll.getString("full_format");
{
if (format.equalsIgnoreCase("pdf"))
{
ext = "pdf";
System.out.println("extension set: "+ext);
}
}
}
filename = filename+"."+ext;
sysObj.getFileEx(filename, ext, 0, false);
}
con.closeConnection(ssn);
//Process p = Runtime.getRuntime().exec("rundll32 url.dll,FileProtocolHandler "+filename);
response.setContentType("application/pdf");
response.setHeader("Content-Disposition", "inline; filename='"+filename+"'");
I'm able to open the pdf file in adobe acrobat reader but it is failing for browser with this error.
Please help me understand where I'm going wrong here.
You need your server to respond with a pdf file. You set the response headers, but your code never writes the pdf data into the response.
Do that using
response.write(bytesFromPdfFile)

Why does the file name appear garbled when using easyExcel to export the excel file?

Why does the file name appear garbled when using easyExcel to export the excel file?
The browser used is chrome.
The output file name is %3F%3F%3F%3F%3F%3F%3F%3F2020-08-28 11_11_28.xlsx
public String encodeFileName(String userAgent, String fileName){
try{
fileName = StringUtils.contains(userAgent, "Mozilla") ? URLEncoder.encode(fileName, "ISO8859-1") : URLEncoder.encode(fileName, "UTF-8");
return fileName;
} catch (UnsupportedEncodingException e){
e.printStackTrace();
return fileName;
}
}
final String userAgent = request.getHeader("USER-AGENT");
String encodeFileName = encodeFileName(userAgent,"流程管理名单")+ DateUtil.getyyyyMMddHHmmss(new Date())+".xlsx";
response.setContentType("application/vnd.ms-excel");
response.setHeader("content-Disposition",
"attachment;filename=" + encodeFileName);
out = response.getOutputStream();
Why does the file name appear garbled when using easyExcel to export the excel file?
ISO8859-1 does not support characters you're trying to encode.
You can simply encode the filename using UTF-8:
public String encodeFileName(String userAgent, String fileName) {
fileName = URLEncoder.encode(fileName, StandardCharsets.UTF_8);
return fileName;
}
Or, if you're using Spring 5+ use ContentDisposition:
String contentDisposition = ContentDisposition.builder("attachment")
.filename("流程管理名单.xlsx")
.build()
.toString();
response.setHeader("Content-Disposition", contentDisposition);
See also
"Downloading a file from spring controllers" (there is my answer giving some additional details about ContentDisposition usage)

file.getName() returns nothing

I need to get the name of a CSV file selected for the user, but the getName() method does not return any value.
This is the code
private void readCSV(Uri uri) {
InputStream is;
File file = null;
try {
if (uri.getScheme().equals("file")) {
file = new File(uri.toString());
Log.i("File selected: ", file.getName()); //file.getName() doesn't work
is = new FileInputStream(file);
Why does this not return the name of the file?
Edit 1
private void readCSV(Uri uri) {
InputStream is;
File file;
try {
/*This conditional is false*/
if (uri.getScheme().equals("file")) {
file = new File(uri.toString());
Log.i("File selected: ", file.getName()); //file.getName() doesn't
is = new FileInputStream(file);
} else {
/* this part is the one that runs */
is = this.getContentResolver().openInputStream(uri);
Log.i("File selected: ", uri.getLastPathSegment()); //i tried this, it returns me 5049 but it is not the name of the selected file
}
uri.toString() will return the object reference but not the file path.
You should call uri.getPath()
Use
new File(uri.getPath());
instead of
new File(uri.toString());
NOTE: uri.toString() returns a String in the format: "file:///mnt/sdcard/image.jpg", whereas uri.getPath() returns a String in the format: "/mnt/sdcard/image.jpg".
try this
fileName = uri.getLastPathSegment();
Getting file names through the apachecommons io lib https://commons.apache.org/proper/commons-io/javadocs/api-2.5/org/apache/commons/io/FilenameUtils.html
String name = FileNameUtils.getName(uri.getPath());

Java BufferedWriter exporting file/directory listing .replaceAll alternative?

Exporting a given directory and file list to a file using BufferedWriter on Java8 (Eclipse IDE). This is working fine.
Some files have special characters like "[", "]" or extensions such as ".zip" that I wish to strip out when saving my file. Tried .replaceALL but getting stuck with how to make this work. Any suggestions please?
public static void getDirectoryList() throws IOException
{
String path = "C:\\Users\\";
File folder = new File(path);
File[] listOfFiles = folder.listFiles();
File file = new File("DirectoryList.txt");
if (!file.exists()) {
file.createNewFile();
}
FileWriter fw = new FileWriter(file.getName());
BufferedWriter bw = new BufferedWriter(fw);
for (File f : listOfFiles) {
// .replaceALL wants to be cast. Is there an alternative to
// .replaceAll when listing out a file listing to file.
// Or, am I doing something silly....
f = f.replaceAll(".zip", "");
bw.write(f.getName());
bw.newLine();
}
bw.close();
}
Example of Current text file output:
[name1].doc <-trying to remove "[" and "]" when saving name to file.
filename.zip <-trying to remove ".zip" when saving name to file.
directoryname1
directoryname2
(Original file and directory names remain, only the results save to the file are being changed.)
Required text file output
name1.doc
filename
directoryname1
directoryname2
replaceAll isn't a method of File, it's a method of String.
for(File f : listOfFiles) {
String fileName = f.getName();
fileName = fileName.replaceAll("\\.zip", "");
fileName = fileName.replaceAll("\\[", "");
fileName = fileName.replaceAll("]", "");
bw.write(fileName);
bw.newLine();
}
Also notice that when I use replaceAll to remove '.zip' from the filename the . must be escaped. That's because the first parameter of replaceAll is a regex and dot . is a special character. The same for [.
There is a more compact way to do the same thing with a single regex
for(File f : new File("").listFiles()) {
String fileName = f.getName();
fileName = fileName.replaceAll("\\.zip|\\[|]", "");
bw.write(fileName);
bw.newLine();
}

Categories