Read windows filename from file in Java - java

Background
For a program I'm writing I need to be able to read Windows filenames from a file. Unfortunately, Windows use \ instead of /, which makes this tricky. I've been trying different ways, but it never seems to work. Here's the Java code:
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
public class Test {
static String localFile;
static String localFilePrefix;
static String user;
public static void main(String[] args){
readConfig("user.txt");
}
public static boolean readConfig(String cfgFilePath){
try{
BufferedReader reader = new BufferedReader(new FileReader(cfgFilePath));
try{
String line;
while((line = reader.readLine()) != null){
if(line.indexOf("User") != -1){
user = line.substring(line.indexOf(" ")+1);
}else if(line.indexOf("LocalFile") != -1){
String tmp = line.substring(line.indexOf(" ")+1);
System.out.println("Test: " + tmp);
setLocalFile(tmp);
}
}
}catch(IOException ee){
System.err.println(ee.getMessage());
}
}catch(FileNotFoundException e){
System.err.println(e.getMessage());
}
return true;
}
public static void setLocalFile(String lFileName){
System.out.println("FileName: " + lFileName);
localFile = lFileName;
if(new File(localFile).isDirectory()){
System.out.println("Here!");
localFilePrefix=localFile+File.separator;
}
}
}
And here is the config file:
User test
LocalFile C:\User
Running this code, whith that file path, doesn't print Test: C:\Users, which it should. Neither does it print FileName: C:\Users or Here!. If I remove "Users" from the file path, however, it works fine and prints everything it's supposed to. It even recognizes C:\ as a directory.
Question
I don't want the user to be forced to write the file path in a special format just because my program can't handle it. So how can I fix this?

Your first condition line.indexOf("User") != -1 is true for the input User test but also for LocalFile C:\User (and it will be so for every path that contains User). Therefore, the else if condition is not evaluated.
Use .startsWith instead of .indexOf
while ((line = reader.readLine()) != null) {
if (line.startsWith("User")) {
user = line.substring(line.indexOf(" ") + 1);
} else if (line.startsWith("LocalFile")) {
String tmp = line.substring(line.indexOf(" ") + 1);
System.out.println("Test: " + tmp);
setLocalFile(tmp);
}
}

Related

how to split one text into multiple text files

I have the following Text:
1
(some text)
/
2
(some text)
/
.
.
/
8519
(some text)
and I want to split this text into several text-files where each file has the name of the number before the text i.e. (1.txt, 2.txt) and so on, and the content of this file will be the text.
I tried this code
BufferedReader br = new BufferedReader(new FileReader("(Path)\\doc.txt"));
try {
StringBuilder sb = new StringBuilder();
String line = br.readLine();
while (line != null) {
sb.append(line);
// sb.append(System.lineSeparator());
line = br.readLine();
}
String str = sb.toString();
String[] arrOfStr = str.split("/");
for (int i = 0; i < arrOfStr.length; i++) {
PrintWriter writer = new PrintWriter("(Path)" + arrOfStr[i].charAt(0) + ".txt", "UTF-8");
writer.println(arrOfStr[i].substring(1));
writer.close();
}
System.out.println("Done");
} finally {
br.close();
}
this code works for files 1-9. However, things go wrong for files 10-8519 since I took the first number in the string (arrOfStr [i].charAt(0)) I know my solution is insufficient any suggestions?
In addition to my comment, considering there isn't a space between the leading integer and the first word, the substring at the first space doesn't work.
This question/answer has a few options that should help, the one using regex (\d+) being the simplest one imo, and copied below.
Matcher matcher = Pattern.compile("\\d+").matcher(arrOfStr[i]);
matcher.find();
int yourNumber = Integer.valueOf(matcher.group());
Given a string find the first embedded occurrence of an integer
As you mentioned, the problem is that you only take the first digit. You could enumerate the first characters until you find a non digit character ( arrOfStr[i].charAt(j) <'0' || arrOfStr[i].charAt(j) > '9' ) but it shoud be easier to user a Scanner and an appropriate regexp.
int index = new Scanner(arrOfStr[i]).useDelimiter("\\D+").nextInt();
The delimiter is precisely any group of non-digit character
Here is a quick solution for the given problem. You can test and do proper exception handling.
package practice;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.List;
public class FileNioTest {
public static void main(String[] args) {
Path path = Paths.get("C:/Temp/readme.txt");
try {
List<String> contents = Files.readAllLines(path);
StringBuffer sb = new StringBuffer();
String folderName = "C:/Temp/";
String fileName = null;
String previousFileName = null;
// Read from the stream
for (String content : contents) {// for each line of content in contents
if (content.matches("-?\\d+")) { // check if it is a number (based on your requirement)
fileName = folderName + content + ".txt"; // create a file name with path
if (sb != null && sb.length() > 0) { // this means if content present to write in the file
writeToFile(previousFileName, sb); // write to file
sb.setLength(0); // clearing buffer
}
createFile(fileName); // create a new file if number found in the line
previousFileName = fileName; // store the name to write content in previous opened file.
} else {
sb.append(content); // keep storing the content to write in the file.
}
System.out.println(content);// print the line
}
if (sb != null && sb.length() > 0) {
writeToFile(fileName, sb);
sb.setLength(0);
}
} catch (IOException ex) {
ex.printStackTrace();// handle exception here
}
}
private static void createFile (String fileName) {
Path newFilePath = Paths.get(fileName);
if (!Files.exists(newFilePath)) {
try {
Files.createFile(newFilePath);
} catch (IOException e) {
System.err.println(e);
}
}
}
private static void writeToFile (String fileName, StringBuffer sb) {
try {
Files.write(Paths.get(fileName), sb.toString().getBytes(), StandardOpenOption.APPEND);
}catch (IOException e) {
System.err.println(e);
}
}
}

Get serial number of hard disk in java by Mac computer?

I'm building a simple class in Java that return the serial number of disk of computer. So this is the code:
package utility;
import java.io.File;
import java.io.FileWriter;
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class TestReadSerialNumber {
private TestReadSerialNumber() { }
public static String getSerialNumber(String drive) {
String result = "";
try {
File file = File.createTempFile("realhowto",".vbs");
file.deleteOnExit();
FileWriter fw = new java.io.FileWriter(file);
String vbs = "Set objFSO = CreateObject(\"Scripting.FileSystemObject\")\n"
+"Set colDrives = objFSO.Drives\n"
+"Set objDrive = colDrives.item(\"" + drive + "\")\n"
+"Wscript.Echo objDrive.SerialNumber"; // see note
fw.write(vbs);
fw.close();
Process p = Runtime.getRuntime().exec("cscript //NoLogo " + file.getPath());
BufferedReader input =
new BufferedReader
(new InputStreamReader(p.getInputStream()));
String line;
while ((line = input.readLine()) != null) {
result += line;
}
input.close();
}
catch(Exception e){
e.printStackTrace();
}
return result.trim();
}
public static void main(String[] args){
String sn = TestReadSerialNumber.getSerialNumber("C");
System.out.println(sn);}
}
Now if I try to start this code from a Windows, I have the correct result. If I try to start this code on a Mac Computer, I don't have never string from getSerialNumber method.
I think that the problem is in the System Operation and my code is compatible only with Windows and not with Mac.
Then, how can I get the serial number by Mac computer ?

Java: Read from Multiple Lines (External File)

I am trying to display the contents of multiple rows in a text file. I can do it no problem with a single line, but I add another line and I'm not sure what I need to add to my code to make it move on to the next line. I need myValues[1] to be the same as myValues[n] only to be the second line in the file. I believe I need to se a new String as the next line but I'm not sure exactly how with this setup.
package a3;
import java.io.*;
public class A3
{
public static void main(String [] args)
{
String animals = "animals.txt";
String line = null;
try
{
FileReader fileReader = new FileReader(animals);
BufferedReader bufferedReader = new BufferedReader(fileReader);
String aLine = bufferedReader.readLine();
String myValues[] = aLine.split(" ");
int n = 0;
while((line = bufferedReader.readLine()) != null)
{
System.out.println(myValues[n] + " " + myValues[1]);
n++;
}
bufferedReader.close();
}
catch(FileNotFoundException ex)
{
System.out.println("Unable to open file '" + animals + "'");
}
catch(IOException ex)
{
System.out.println("Error reading file '" + animals + "'");
}
}
}
Here is another simple way to read lines from a file and do the processing:
There is a java.io.LineNumberReader class which helps do it.
Sample snippet:
LineNumberReader lnr = new LineNumberReader(new FileReader(new File(filename)));
String line = null;
while ((line = lnr.readLine()) != null)
{
// Do you processing on line
}
In your code, the array myValues is never changed and always contains the values for the first line of text. You need to change it each time you get a new line, this is done in your while loop :
[...]
while((line = bufferedReader.readLine()) != null)
{
myValues[] = line.split(" ");
System.out.println(myValues[n] + " " + myValues[1]);
n++;
}
Obviously not tested...
You could also read all lines to a String list like this:
import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.util.List;
List<String> lines = Files.readAllLines(new File(animals).toPath(), Charset.defaultCharset());
And than iterate over the line list, split the values and output them.

Windows 7 & Java: Get Disk-identifier

I have a hdd array with 4 encrypted hard-drives (truecrypt). I recently switched back from 5 years of linux to windows 7 and I find myself confronted with a problem I can't find a solution for.
Under linux there was a command called "fdisk" which gives you all running (not mounted!) harddrives plus a unique disk-identifier which doesn't change (something like: Disk Identifier: 00x33f1a3c1).
I need that same functionality under Windows, preferably writing the code in java.
cheers
edit:// For clarification, I need the Disk-ID without mounting the Disk!
A solution using VBS.
import java.io.File;
import java.io.FileWriter;
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class DiskUtils {
private DiskUtils() { }
public static String getSerialNumber(String drive) {
String result = "";
try {
File file = File.createTempFile("realhowto",".vbs");
file.deleteOnExit();
FileWriter fw = new java.io.FileWriter(file);
String vbs = "Set objFSO = CreateObject(\"Scripting.FileSystemObject\")\n"
+"Set colDrives = objFSO.Drives\n"
+"Set objDrive = colDrives.item(\"" + drive + "\")\n"
+"Wscript.Echo objDrive.SerialNumber";
fw.write(vbs);
fw.close();
Process p = Runtime.getRuntime().exec("cscript //NoLogo " + file.getPath());
BufferedReader input =
new BufferedReader
(new InputStreamReader(p.getInputStream()));
String line;
while ((line = input.readLine()) != null) {
result += line;
}
input.close();
}
catch(Exception e){
e.printStackTrace();
}
return result.trim();
}
public static void main(String[] args){
String sn = DiskUtils.getSerialNumber("C");
javax.swing.JOptionPane.showConfirmDialog((java.awt.Component)
null, sn, "Serial Number of C:",
javax.swing.JOptionPane.DEFAULT_OPTION);
}
}

Filewriter and spaces?

I was asked to write an assignment wherein the user would be prompted to input a key and/or a value.
So far, here is my code:
import java.util.Scanner;
import java.io.*;
class bTree
{
//Fields
static Scanner input = new Scanner(System.in);
static boolean done = false;
public static void main(String args[])throws Exception
{
FileWriter fWriter = new FileWriter("data.txt");
do
{
System.out.print("Enter command: ");
String enter[] = input.nextLine().split(" ", 3);
if(enter[0].toLowerCase().equals("insert"))
{
fWriter.write(enter[1] + "\n" + enter[2] + "\n");
fWriter.flush();
}
else if(enter[0].toLowerCase().equals("select"))
{
FileReader fReader = new FileReader("data.txt");
Scanner fileInput = new Scanner(fReader);
while(fileInput.hasNext() && done == false)
{
if(fileInput.nextLine().equals(enter[1]))
{
System.out.println(fileInput.nextLine());
done = true;
}
else
{
fileInput.nextLine();
}
}
done = false;
}
else if(enter[0].toLowerCase().equals("update"))
{
fWriter.write(enter[2]);
fWriter.flush();
}
else if(enter[0].toLowerCase().equals("exit"))
{
System.exit(0);
}
}
while(true);
}
}
Problem: When i open the data.txt, there are no spaces. So if i enter "insert 1001 gen" and "10001 genny", in notepad, it would come out as "1001gen10001genny". Any suggestions?
The problem is that notepad.exe is picky about line endings, and there are many possibilities. When you write "\n" to a FileWriter, it writes a single character, namely '\n'. But notepad expects the sequence "\r\n" instead. It shows a single "\n" as nothing.
Here is your code, slightly modified to work around some pitfalls.
package so7696816;
import java.io.FileReader;
import java.io.PrintWriter;
import java.util.Locale;
import java.util.Scanner;
public class Excercise {
public static void main(String args[]) throws Exception {
final Scanner input = new Scanner(System.in);
PrintWriter fWriter = new PrintWriter("data.txt");
while (true) {
System.out.print("Enter command: ");
String enter[] = input.nextLine().split(" ", 3);
final String command = enter[0].toLowerCase(Locale.ROOT);
if (command.equals("insert")) {
fWriter.println(enter[1]);
fWriter.println(enter[2]);
fWriter.flush();
} else if (command.equals("select")) {
FileReader fReader = new FileReader("data.txt");
Scanner fileInput = new Scanner(fReader);
while (fileInput.hasNextLine()) {
String key = fileInput.nextLine();
String value = fileInput.nextLine();
if (key.equals(enter[1])) {
System.out.println(value);
break;
}
}
fReader.close(); // don't leave files open
} else if (command.equals("update")) {
fWriter.write(enter[2]);
fWriter.flush();
} else if (command.equals("exit")) {
return;
} else {
System.err.println("Unknown command: " + command);
}
}
}
}
Remarks:
I used a PrintWriter instead of a FileWriter to get the line endings correct.
For the select command I closed the fReader after using it.
I avoided to type enter[0].toLowerCase() multiple times.
I used the proper variant of toLowerCase.
I added error handling for unknown commands.
I rewrote the select command to be a little more concise.
The problem is String enter[] = input.nextLine().split(" ", 3);, it kills the Spaces. So append a space after each array entry or write an additional " " everytime you use fWriter.write.
look here
As already stated the line feed character is incorrect for notepad. Alternatively you could wrap that FileWriter in a BufferedWriter and use the newLine method to always insert the correct line feed.
I think you are running your program in UNIX. In unix system "\r\n" is the line feed.
If you are running your program in Windows, I think the file should contain something like this.
1001
gen
10001
genny

Categories