Attempting to append number chars in a filename to a new file - java

I am attempting in Java to grab a file name, select the first eight characters from this file name and then append them to a new file name, I'm not entirely sure how to go about this and I'm not entirely sure my approach is even the correct way to go about this but here is my attempt so far: (Above this I have code to copy a new file from one directory to another this works)
for (String file : files) {
File srcFile = new File(src, file);
String fileName = null;
new File(fileName).getName();
String fileNames;
fileNames = "Split after 8 characters!";
if (fileNames.length() > 16)
fileNames = fileNames.substring(0, 8) + "...";
File destFile = new File(dest, file);
copyFolder(srcFile,destFile);
fileName.renameTo(fileNames);
}
The only thing giving me an error at the moment is the .renameTo at the bottom and the error given is
cannot find symbol symbol: method renameTo(String) location:
variable fileName of type String Dereferencing null pointer

Related

How to rename a file before insert to a path Java?

I need to insert a file to a path. However, the file name need to change to a specific name before inserted.
How can I change the name of the file before insert to path? As many resources online only able to change the file name after inserted. Online Resource for rename file
My code currently
String localPath = "c://Users/foody/Documents/write_file_local/";
String finalPath = localPath + file.getOriginalFilename();
File uploadPath = new File(finalPath);
if (!uploadPath.getParentFile().exists()) {
uploadPath.getParentFile().mkdirs();
}
//I think need to rename the file here before insert to path
byte[] bytes = file.getBytes();
Path path = Paths.get(finalPath);
Files.write(path, bytes);
Replace your code with this and update your "CustomName_ABC" with your new fileName.
String localPath = "c://Users/foody/Documents/write_file_local/";
String finalPath = localPath + "CustomName_ABC";
File uploadPath = new File(finalPath);
if (!uploadPath.getParentFile().exists()) {
uploadPath.getParentFile().mkdirs();
}
Files.copy(file.toPath(), uploadPath.toPath());
You can copy your old file to a new filePath (directory) by using Files.copy() method. It will take two parameters:
Old file path
New file path

Java: How do I access my properties file?

So I have a property file in my project. I need to access it.
Here's the tree structure:
+ Project Name
|--+ folder1
|--+ propertyfolder
|--+ file.properties
Or: Project/propertyfolder/file.properties
Here's what I've tried so far (one at a time, not all at once):
// error: java.io.File.<init>(Unknown Source)
File file = new File(System.getProperty("file.properties"));
File file = new File(System.getProperty("propertyfolder/file.properties"));
File file = new File(System.getProperty("propertyfolder\\file.properties"));
File file = new File(System.getProperty("../../propertyfolder/file.properties"));
And:
InputStream inputStream = getClass().getResourceAsStream("file.properties");
InputStream inputStream = getClass().getResourceAsStream("../../propertyfolder/file.properties");
InputStream inputStream = getClass().getResourceAsStream("propertyfolder/file.properties");
InputStream inputStream = getClass().getResourceAsStream("propertyfolder\\file.properties");
And all variations within getClass(), such as getClass().getClassLoader(), etc.
The error I'm getting is a NullReferenceException. It's not finding the file. How do I find it correctly?
(taken from comment to answer as OP suggested)
Just use File file = new File("propertyfolder/file.properties") but you do need to know where is java process working directory, if you cannot control it try an absolute path /c:/myapp/propertyfolder/file.properties.
You may also use /myapp/propertyfolder/file.properties path without C: disk letter to avoid windows-only mapping. You may use / path separator in Java apps works in Win,Linux,MacOSX. Watch out for text file encoding, use InputStreamReader to given an encoding parameter.
File file = new File("propertyfolder/file.properties");
InputStreamReader isr = new InputStreamReader(new FileInputStream(file), "UTF-8");
BufferedReader reader = new BufferedReader(isr);
..read...
reader.close(); // this will close underlaying fileinputstream
Inorder to use getClass().resourceAsStream("file.properties") you need to make sure the file is there in the classpath.
That is if your Test.java file is compiled into bin/Test.class then make sure to have file.properties in the bin/ folder along with the Test.class
Otherwise you can use the Absolute Path, which is not advisable.
Did you set System properties to load file.properties from
1) Command line using -Dpropertyname=value OR
2) System.setProperty() API OR
3) System.load(fileName) API?
If you have n't done any one of them, do not use System.getProperty() to load file.properties file.
Assuming that you have not done above three, the best way to create file InputStream is
InputStream inputStream = getClass().getResourceAsStream("<file.properties path from classpath without />");
Properties extends Hashtable so, Each key and its corresponding value in the property list is a string.
Properties props = new Properties();
// File - Reads from Project Folder.
InputStream fileStream = new FileInputStream("applicationPATH.properties");
props.load(fileStream);
// Class Loader - Reades Form src Folder (Stand Alone application)
ClassLoader AppClassLoader = ReadPropertyFile.class.getClassLoader();
props.load(AppClassLoader.getResourceAsStream("classPATH.properties"));
for(String key : props.stringPropertyNames()) {
System.out.format("%s : %s \n", key, props.getProperty(key));
}
// Reads from src folder.
ResourceBundle rb = ResourceBundle.getBundle("resourcePATH");// resourcePATH.properties
Enumeration<String> keys = rb.getKeys();
while(keys.hasMoreElements()){
String key = keys.nextElement();
System.out.format(" %s = %s \n", key, rb.getString(key));
}
// Class Loader - WebApplication : src folder (or) /WEB-INF/classes/
ClassLoader WebappClassLoader = Thread.currentThread().getContextClassLoader();
props.load(WebappClassLoader.getResourceAsStream("webprops.properties"));
To read properties from specific folder. Construct path form ProjectName
InputStream fileStream = new FileInputStream("propertyfolder/file.properties");
If Key:value pairs specified in .txt file then,
public static void readTxtFile_KeyValues() throws IOException{
props.load(new FileReader("keyValue.txt") );
// Display all the values in the form of key value
for (String key : props.stringPropertyNames()) {
String value = props.getProperty(key);
System.out.println("Key = " + key + " \t Value = " + value);
}
props.clear();
}

Create directory using a variable as the name

Maybe its something simple i am over looking, but i need to be able to create sub directories using a list of numbers stored in a txt file. When i use a string literal it creates the directory, but when i switch to using the variable being used for the items in the list it will not. Here is the code block.
private static void GetJarDir() throws URISyntaxException {
CodeSource codeSource = NewJFrame.class.getProtectionDomain().getCodeSource();
File jarFile = null;
jarFile = new File(codeSource.getLocation().toURI().getPath());
jarDir = jarFile.getParentFile().getPath().replace("dist", "").replace("build", "");
mainFolder = jarDir + "Invoices\\";
}
this is the method i use to get the directory for the jar file and append the path with the directory i need to create the sub-directories in, i'm sure this works.
BufferedImage dest = image.getSubimage(0, 3377, 465, 80);
String newDir = new OCR().recognizeEverything(dest);
File theDir = new File(mainFolder + newDir);
new File(mainFolder + newDir.mkdirs();
im using an optical character recognition library to grab an invoice number off of a cropped image. So newDir is the invoice number. Ive printed out the path and it is the correct path, it is just not creating the directory. If i change the variable to the actual invoice number it works, any ideas?
new File(mainFolder + "223545").mkdirs();
so sitting here playing with it ive narrowed the problem down to the string returned from the OCR. It has to be a string or it wouldnt compile...but when i try to parse the string to an int it throws an exception. and it is in fact an integer

Weird exception in thread "main" java.io.FileNotFoundException I/O Java

I have this error when I am trying to read the file:
Exception in thread "main" java.io.FileNotFoundException: \src\product.txt (No such file or directory)
at java.io.FileInputStream.open(Native Method)
at java.io.FileInputStream.<init>(FileInputStream.java:120)
at dao.Inventory.readFile(Inventory.java:30)
at view.InventoryView.init(InventoryView.java:33)
at view.InventoryView.<init>(InventoryView.java:21)
at view.InventoryView.main(InventoryView.java:211)
But the thing is, I have the product.txt in my src folder.
My code is the following:
public void readFile() throws IOException {
// input file must be supplied in the first argument
InputStream istream;
File inputFile = new File("\\src\\product.txt");
istream = new FileInputStream(inputFile);
BufferedReader lineReader;
lineReader = new BufferedReader(new InputStreamReader(istream));
String line;
while ((line = lineReader.readLine()) != null) {
StringTokenizer tokens = new StringTokenizer(line, "\t");
// String tmp = tokens.nextToken();
// System.out.println("token " + tmp);
ActionProduct p = new ActionProduct();
prodlist.add(p);
String category = p.getCategory();
category = tokens.nextToken();
System.out.println("got category " +category);
int item = p.getItem();
item = Integer.parseInt(tokens.nextToken());
String name = p.getName();
System.out.println("got name " +name);
double price = p.getPrice();
price = Double.parseDouble(tokens.nextToken());
int units = p.getUnits();
units = Integer.parseInt(tokens.nextToken());
}
}
I don't think anything is wrong with my code. Also, I saw a similar post about a hidden extension like FILE.TXT.TXT, how would you show a hidden extension in MacOSX?? Any suggestions? (Would there be any other problem besides the hidden extension issue?)
/src/product.txt is an absolute path, so the program will try to find the file in the src folder of your root path (/). Use src/product.txt so the program will use this as a relative path.
It's possible (most likely?) that your Java code is not executing inside the parent folder of src, but instead inside a 'class' or a 'bin' folder with the compiled java .class files.
Assuming that 'src' and 'bin' are in the same directory, you could try ..\\src\\product.txt
See also http://en.wikipedia.org/wiki/Path_(computing)
As other commenters stated, the path is absolute and points to
\src\product.txt which is (hopefully) not where
your sources are stored.
The path separator should be set in an OS-independent manner using
the System.getProperty("path.separator") property. On a Unix system, you'll have trouble with hard coded backslashes as path separators. Keep it portable!
String pathSeparator = System.getProperty("path.separator");
String filePath = "." + pathSeparator + "src" + pathSeparator + "product.txt";
File file = new File(filePath);
or better yet:
// this could reside in a non-instantiable helper class somewhere in your project
public static String getRelativePath(String... pathElements) {
StringBuilder builder = new StringBuilder(".");
for (String pathElement : pathElements) {
builder.append(System.getProperty("path.separator");
builder.append(pathElement);
}
return builder.toString();
}
// this is where your code needs a path
...
new File(getRelativePath("src", "product.txt");
...

create a text file in a folder

I want to create a text file into that folder that I am creating here.
File dir = new File("crawl_html");
dir.mkdir();
String hash = MD5Util.md5Hex(url1.toString());
System.out.println("hash:-" + hash);
File file = new File(""+dir+"\""+hash+".txt");
But this code doesn't create the text file into that folder..Instead it makes the text file outside that folder..
One of java.io.File's constructors takes a parent directory. You can do this instead:
final File parentDir = new File("crawl_html");
parentDir.mkdir();
final String hash = "abc";
final String fileName = hash + ".txt";
final File file = new File(parentDir, fileName);
file.createNewFile(); // Creates file crawl_html/abc.txt
What you need is
File file = new File(dir, hash + ".txt");
The key here is the File(File parent, String child) constructor. It creates a file with the specified name under the provided parent directory (provided that directory exists, of course).
The line
new File(""+dir+"\""+hash+".txt");
makes a file named crawl_html"the_hash.txt, because \" inside a String literal is used to represent a double quote caracter, not a backslash. \\ must be used to represent a backslash.
Use the File constructor taking a File (directory) as the first argument, and a file name as a second argument:
new File(dir, hash + ".txt");
your path-delimiter seems off
try:
File file = new File ( "" + dir + "/" + hash + ".txt" );

Categories

Resources