Ok, so im writing a program that transfers files from my usb to a computer (so i can set up stuff quickly for something im doing on monday) and im trying to make it make a shortcut on the desktop so that you dont have to go into the source folder of the files transfered so you can start up the program again in case you exit it. heres my code, and the title is the error im getting.
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
public class Mover {
public static void main(String[] args) throws IOException, InterruptedException {
String usb = new File(".").getAbsolutePath();
String desktop = System.getProperty("user.home") + "/Desktop";
File srcFolder = new File(usb + "/Teamspeak 3");
File destFolder = new File(desktop + "/TS3");
//make sure source exists
if(!srcFolder.exists()){
System.out.println("Directory does not exist.");
//just exit
System.exit(0);
}else{
try{
copyFolder(srcFolder,destFolder);
}catch(IOException e){
e.printStackTrace();
//error, just exit
System.exit(0);
}
}
System.out.println("Done");
String cmd = "ls -al";
Runtime run = Runtime.getRuntime();
Process pr = run.exec(cmd);
pr.waitFor();
BufferedReader buf = new BufferedReader(new InputStreamReader(pr.getInputStream()));
String line = "-shortcut -t c:/ocuments and Settings/%username%/Desktop/TS3/ts3client_win32.exe" "-n Teamspeak 3.lnk";
while ((line=buf.readLine())!=null) {
System.out.println(line);
Process process = Runtime.getRuntime ().exec (desktop + "/TS3/ts3client_win32.exe");
System.exit(0);
}
}
public static void copyFolder(File src, File dest)
throws IOException{
if(src.isDirectory()){
//if directory not exists, create it
if(!dest.exists()){
dest.mkdir();
System.out.println("Directory copied from "
+ src + " to " + dest);
}
//list all the directory contents
String files[] = src.list();
for (String file : files) {
//construct the src and dest file structure
File srcFile = new File(src, file);
File destFile = new File(dest, file);
//recursive copy
copyFolder(srcFile,destFile);
}
}else{
//if file, then copy it
//Use bytes stream to support all file types
InputStream in = new FileInputStream(src);
OutputStream out = new FileOutputStream(dest);
byte[] buffer = new byte[1024];
int length;
//copy the file content in bytes
while ((length = in.read(buffer)) > 0){
out.write(buffer, 0, length);
}
in.close();
out.close();
System.out.println("File copied from " + src + " to " + dest);
}
}
}
String line = "-shortcut -t c:/ocuments and Settings/%username%/Desktop/TS3/ts3client_win32.exe" "-n Teamspeak 3.lnk";
This line seems malformed. You have two strings without + in between.
Related
Good Morning. Having trouble with a parser using split method. Goal is to read in txt file, extract should statements, then write a new txt file with those should statements. I have it working when the text is on one continuous line. If I have a new line in the txt file, rewrites the file with just the last line. Possibly the structure of my loops? Also any suggestions for saving new file from the directory in which it was opened? Thank you
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
/*This Program Will launch a File Explorer.
User will then chose a .txt file to be parsed.
A new file will be created labeled "Parsed_(Document Name)".*/
public class Parser {
#SuppressWarnings("resource")
public static void main(String[] args) {
JFileChooser chooser = new JFileChooser();
Scanner userFile = new Scanner(System.in);
int returnVal = chooser.showOpenDialog(null);
if (returnVal == JFileChooser.APPROVE_OPTION) {
try {
System.out.println("You chose to open this file: " + chooser.getSelectedFile().getName() + "\n");
File file = new File(chooser.getSelectedFile().getName());
String newFile = ("Parsed_" + file);
userFile = new Scanner(file);
while (userFile.hasNextLine()) {
String document = userFile.nextLine();
// Line breaks used by Parser
String[] sentences = document.split("\\.|\\?|\\!|\\r");
List<String> ShouldArray = new ArrayList<String>();
for (String shouldStatements : sentences) {
if (shouldStatements.contains("Should") || shouldStatements.contains("should"))
ShouldArray.add(shouldStatements);
}
FileWriter writer = new FileWriter(newFile);
BufferedWriter bw = new BufferedWriter(writer);
for (String shallStatements : ShouldArray) {
System.out.println(shallStatements);
bw.append(shallStatements);
bw.newLine();
}
System.out.println("\nParsed Document Created: " + newFile);
JOptionPane.showMessageDialog(null, "Parsed Document Created: " + newFile);
bw.close();
writer.close();
}
userFile.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
}
Test file 1 (works!)
Hello all. Here is a a packing list. You Should have a toothbrush. You should have a Phone charger. And you definitely should have your wallet!
Test file 1 output:
You Should have a toothbrush
You Should have a Phone charger
And you definitely should have your wallet
Test file 2 (Only printing last line)
Hello all. Here is a a packing list. You Should have a toothbrush. You Should have a Phone charger.
Here is some random text to show the parser will not include this.
You definitely should have your wallet!
test file 2 output:
You definitely should have your wallet
You need to create your result array outside of the loop
/** Placed here**/
List<String> ShouldArray = new ArrayList<String>();
while (userFile.hasNextLine()) {
String document = userFile.nextLine();
// Line breaks used by Parser
String[] sentences = document.split("\\.|\\?|\\!|\\r");
/** REMOVED HERE **/
for (String shouldStatements : sentences) {
if (shouldStatements.contains("Should") || shouldStatements.contains("should"))
ShouldArray.add(shouldStatements);
}
......
otherwise you will only gather the results of your last loop.
Basically what your code was doing:
cut up file in lines
take each line
take next line
make a result board.
write results on board
take next line
erase board
write results on board
take next line
erase board
write results on board
and then at the end there is only a limited resultset on your board
You are overriding your Arraylist within the loop, however you don't actually need it
File file = chooser.getSelectedFile();
System.out.println("You chose to open this file: " + file.getName() + "\n");
String newFile = "Parsed_" + file.getName();
// open all closable objects using try-with-resources
try (Scanner userFile = new Scanner(file);
BufferedWriter bw = new BufferedWriter(new FileWriter(newFile))) {
while (userFile.hasNextLine()) {
String document = userFile.nextLine();
// Line breaks used by Parser
String[] sentences = document.split("\\.|\\?|\\!|\\r");
for (String s : sentences) {
if (s.contains("Should") || s.contains("should")) {
System.out.println(s);
bw.append(s);
bw.newLine();
}
}
System.out.println("\nParsed Document Created: " + newFile);
JOptionPane.showMessageDialog(null, "Parsed Document Created: " + newFile);
// bw.close(); // not needed anymore
I've refactored the code, removing the "ShouldArray", which is not needed.
Pseudocode
While there are lines to read in the In file
Read each line
Split each line into Array of sentences
Loop through each sentence
If each sentence contains Should or should Then
Write sentence to Out file
End If
End Loop
End While
Close Out file
Close In file
The code below works with:
Multi line:
Hello all. Here is a a packing list.
You Should have a toothbrush. You Should have a Phone charger.
Here is some random text to show the parser will not include this.
You definitely should have your wallet!
Single line:
Hello all. Here is a a packing list. You Should have a toothbrush. You should have a Phone charger. And you definitely should have your wallet!
import java.util.Scanner;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.io.File;
public class ShouldStringsParser {
public ShouldStringsParser(String inFile, String outFile) throws IOException {
File file = new File(inFile);
FileWriter writer = new FileWriter(outFile);
BufferedWriter bw = new BufferedWriter(writer);
Scanner userFile;
userFile = new Scanner(file);
String[] sentences;
while (userFile.hasNextLine()) {
String line = userFile.nextLine();
System.out.println(line);
sentences = line.split("\\.|\\?|\\!|\\r");
for (String shouldStatements : sentences) {
if (shouldStatements.contains("Should") || shouldStatements.contains("should")) {
System.out.println(">>>" + shouldStatements);
bw.append(shouldStatements);
bw.newLine();
}
}
}
bw.close();
writer.close();
userFile.close();
}
public static void main(String[] args) {
try {
new ShouldStringsParser("inDataMultiLine.txt", "outDataMultiLine.txt");
new ShouldStringsParser("inDataSingleLine.txt", "outDataSingleLine.txt");
} catch (IOException e) {
e.printStackTrace();
}
}
}
So in C drive, I have a folder called Search Files and inside Search Files, I have four subdirectories called Folder 1, Folder 2, Folder 3, and Folder 4.
Inside of Folder 1, I have a text file called hello.txt and the contents of that file is hello.
My expected output is "Directory of the file" + "file name" + "file body".
Below is the code that I have right now.
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Iterator;
import org.apache.commons.io.FileUtils;
public class FileDirectories {
public static void main(String[] args) throws IOException {
File[] files = new File("C:\\Search Files").listFiles();
showFiles(files);
}
public static void showFiles(File[] files) throws IOException {
String line = null;
try{
for (File file : files) {
if (file.isDirectory()) {
String fileName = "Directory" + file.getName();
//System.out.println("Directory: " + file.getName());
BufferedReader in = new BufferedReader(new FileReader(file));
while((line = in.readLine()) != null)
{
System.out.println(line);
}
in.close();
showFiles(file.listFiles()); // Calls same method again.
} else {
System.out.println("File: " + file.getName() + file.toString());
}
}
}catch(NullPointerException e){
e.printStackTrace();
}
/*Iterator<File> it = FileUtils.iterateFiles(new File("C://Search Files//"), null, false);
while(it.hasNext()) {
System.out.println(((File) it.next()).getName());
}*/
}
}
When I execute the above code, I get the following error:
Exception in thread "main" java.io.FileNotFoundException: C:\Search Files\Folder 1 (Access is denied)
at java.io.FileInputStream.open(Native Method)
at java.io.FileInputStream.<init>(FileInputStream.java:146)
at java.io.FileReader.<init>(FileReader.java:72)
at org.raghav.stuff.FileDirectories.showFiles(FileDirectories.java:27)
at org.raghav.stuff.FileDirectories.main(FileDirectories.java:16)
Once again, I need to get the file directory, the file name, and the contents of the file.
In case of the hello.txt, the expected output should be:
C:\Search Files\Folder1\ hello.txt hello
Can you guys point me in the right directions? How to fix the above exception and how do I get a String that displays the directory, file name, and the contents of the file?
Your code looks okay except you have to organized it as follows especially showFiles method.
public static void showFiles(File[] files) throws IOException {
String line = null;
try{
for (File file : files) {
if (file.isDirectory()) {
String fileName = "Directory: " + file.getName();
System.out.print(fileName);
showFiles(file.listFiles()); // Calls same method again.
} else {
System.out.print("\tFile: " + file.getName() + file.toString());
//System.out.println("Directory: " + file.getName());
BufferedReader in = new BufferedReader(new FileReader(file));
while((line = in.readLine()) != null)
{
System.out.print("\t Content:" + line);
}
in.close();
System.out.println();
}
}
}catch(NullPointerException e){
e.printStackTrace();
}
And the output will look like:
Directory: Folder 1 File: C:\Search Files\Folder 1\test.txt Content:this is a test
Directory: Folder 2 File: C:\Search Files\Folder 2\test.txt Content:this is a test
Directory: Folder 3 File: C:\Search Files\Folder 3\test.txt Content:this is a test
Directory: Folder 4 File: C:\Search Files\Folder 4\test.txt Content:this is a test
so I'm making a java app to find all java files on a directory and then concatenate them into one single file to be put on the same directory but I can't seem to get the concatenation right. Here's what I've done so far hope you guys can help me with it as I've tried various things but still can't get it right. Thanks!
import java.io.File;
import java.io.FileFilter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class FileConcatenate {
public static void main(String[] args) {
String dirName = args[0];
String fileName = args[1];
File dirFile = new File("C:\\Users\\Michael\\Desktop\\" + dirName + "");
File file = new File("C:\\Users\\Michael\\Desktop\\" + dirName + "\\" + fileName + ".java");
FileFilter filter = new FileFilter(){
public boolean accept(File pathname){
if(pathname.getName().contains(".java")){
return true;
}else{
return false;
}
}
};
try{
if(!dirFile.exists()){
System.out.println("There is no directory with that name");
}
File[] javaFile = dirFile.listFiles(filter);
if(!file.exists()){
file.createNewFile();
}
FileWriter fw = new FileWriter(file, true);
for(File f : javaFile){
FileReader fr = new FileReader(f);
fw.write(fr.read());
fr.close();
}
fw.flush();
fw.close();
}catch(IOException e){
e.printStackTrace();
}
}
}
Do in this way. For more info read inline comments.
...
FileWriter fw = new FileWriter(file, true);
for (File f : javaFile) {
FileReader fr = new FileReader(f);
// read 1000 chars at a time from source file
char[] cbuf = new char[1000];
int count = -1;
// iterate till the end of source file
// here count represent the no of chars read at a time
while ((count = fr.read(cbuf)) != -1) {
// write in the targeted file
fw.write(cbuf, 0, count);
}
fr.close();
}
...
In your case fw.write(fr.read()); doesn't do what you are expecting.
It just read one character form the source file and write in the target file.
For more info have a look at InputStreamReader#read() that reads a single character.
Let me just start out by saying I created an account on here because I've been beating my head against a wall in order to try and figure this out, so here it goes.
Also, I have already seen this question here. Neither one of those answers have helped and I have tried both of them.
I need to create a word document with a simple table and data inside. I decided to create a sample document in which to get the xml that I need to create the document. I moved all the folders from the unzipped docx file into my assets folder. Once I realized I couldn't write to the assets folder, I wrote a method to copy all the files and folders over to an external storage location of the device and then write the document I created to the same location. From there Im trying to zip the files back up to a .docx file. This is where things arent working.
The actual docx file is created and I can move it to my computer through the DDMS but when I go to view it Word says its corrupt. Heres whats weird though, if I unzip it and then rezip it on my computer without making any changes what so ever it works perfectly. I have used a program (for mac) called DiffMerge to compare the sample unzipped docx file to the unzipped docx that I have created and it says they are exactly the same. So, I think it has something to do with the zipping process in Android.
I have also tried unzipping the sample docx file on my computer, moving all the files and folders over to my assets folder including the document.xml file and just try to zip it up without adding my own document.xml file and using the sample one and that doesnt work either. Another thing I tried was to place the actual docx file in my assets folder, unzipping it onto my external storage and then rezipping it without doing anything. This also fails.
I'm basically at a loss. Please somebody help me figure this out.
Here is some of my code:
moveDocxFoldersFromAssetsToExternalStorage() is called first.
After that is called all the files have been moved over.
Then, I create the document.xml file and place it in the word directory where it belongs
Everything is where it should be and I now try to create the zip file.
.
private boolean moveDocxFoldersFromAssetsToExternalStorage(){
File rootDir = new File(this.externalPath);
rootDir.mkdir();
copy("");
// This is to get around a glitch in Android which doesnt list files or folders
// with an underscore at the beginning of the name in the assets folder.
// This renames them once they are saved to the device.
// We need it to show up in the list in order to move them.
File relsDir = new File(this.externalPath + "/word/rels");
File renameDir = new File(this.externalPath + "/word/_rels");
relsDir.renameTo(renameDir);
relsDir = new File(this.externalPath + "/rels");
renameDir = new File(this.externalPath + "/_rels");
relsDir.renameTo(renameDir);
// This is to get around a glitch in Android which doesnt list hidden files.
// We need it to show up in the list in order to move it.
relsDir = new File(this.externalPath + "/_rels/rels.rename");
renameDir = new File(this.externalPath + "/_rels/.rels");
relsDir.renameTo(renameDir);
return true;
}
private void copy(String outFileRelativePath){
String files[] = null;
try {
files = this.mAssetManager.list(ASSETS_RELATIVE_PATH + outFileRelativePath);
} catch (IOException e) {
e.printStackTrace();
}
String assetFilePath = null;
for(String fileName : files){
if(!fileName.contains(".")){
String outFile = outFileRelativePath + java.io.File.separator + fileName;
copy(outFile);
} else {
File createFile = new File(this.externalPath + java.io.File.separator + outFileRelativePath);
createFile.mkdir();
File file = new File(createFile, fileName);
assetFilePath =
ASSETS_RELATIVE_PATH + outFileRelativePath + java.io.File.separator + fileName;
InputStream in = null;
OutputStream out = null;
try {
in = this.mAssetManager.open(assetFilePath);
out = new FileOutputStream(file);
copyFile(in, out);
in.close();
out.flush();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
private void copyFile(InputStream in, OutputStream out) throws IOException {
byte[] buffer = new byte[1024];
int read;
while((read = in.read(buffer)) != -1){
out.write(buffer, 0, read);
}
}
private void zipFolder(String srcFolder, String destZipFile) throws Exception{
FileOutputStream fileWriter = new FileOutputStream(destZipFile);
ZipOutputStream zip = new ZipOutputStream(fileWriter);
zip.setMethod(Deflater.DEFLATED);
zip.setLevel(ZipOutputStream.STORED);
addFolderToZip(this.externalPath, "", zip);
zip.finish();
zip.close();
}
private void addFolderToZip(String externalPath, String folder, ZipOutputStream zip){
File file = new File(externalPath);
String files[] = file.list();
for(String fileName : files){
try {
File currentFile = new File(externalPath, fileName);
if(currentFile.isDirectory()){
String outFile = externalPath + java.io.File.separator + fileName;
addFolderToZip(outFile, folder + java.io.File.separator + fileName, zip);
} else {
byte[] buffer = new byte[8000];
int len;
FileInputStream in = new FileInputStream(currentFile);
zip.putNextEntry(new ZipEntry(folder + java.io.File.separator + fileName));
while((len = in.read(buffer)) > 0){
zip.write(buffer, 0, len);
}
zip.closeEntry();
in.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
EDIT
Here is the code I wrote in order to get it working correctly based on what #edi9999 said below. I created a separate class that Im going to expand and add to and probably clean up a bit but this is working code. It adds all the files in a directory to the zip file and recursively calls itself to add all the subfiles and folders.
private class Zip {
private ZipOutputStream mZipOutputStream;
private String pathToZipDestination;
private String pathToFilesToZip;
public Zip(String pathToZipDestination, String pathToFilesToZip) {
this.pathToZipDestination = pathToZipDestination;
this.pathToFilesToZip = pathToFilesToZip;
}
public void zipFiles() throws Exception{
FileOutputStream fileWriter = new FileOutputStream(pathToZipDestination);
this.mZipOutputStream = new ZipOutputStream(fileWriter);
this.mZipOutputStream.setMethod(Deflater.DEFLATED);
this.mZipOutputStream.setLevel(8);
AddFilesToZip("");
this.mZipOutputStream.finish();
this.mZipOutputStream.close();
}
private void AddFilesToZip(String folder){
File mFile = new File(pathToFilesToZip + java.io.File.separator + folder);
String mFiles[] = mFile.list();
for(String fileName : mFiles){
File currentFile;
if(folder != "")
currentFile = new File(pathToFilesToZip, folder + java.io.File.separator + fileName);
else
currentFile = new File(pathToFilesToZip, fileName);
if(currentFile.isDirectory()){
if(folder != "")
AddFilesToZip(folder + java.io.File.separator + currentFile.getName());
else
AddFilesToZip(currentFile.getName());
} else {
try{
byte[] buffer = new byte[8000];
int len;
FileInputStream in = new FileInputStream(currentFile);
if(folder != ""){
mZipOutputStream.putNextEntry(new ZipEntry(folder + java.io.File.separator + fileName));
} else {
mZipOutputStream.putNextEntry(new ZipEntry(fileName));
}
while((len = in.read(buffer)) > 0){
mZipOutputStream.write(buffer, 0, len);
}
mZipOutputStream.closeEntry();
in.close();
} catch (IOException e){
e.printStackTrace();
}
}
}
}
}
I think I've got what's wrong.
When I opened your corrupted File, and opened it on winrar, I saw antislashes at the beginning of the folders, which is unusual:
When I rezip the file after unzipping it, the antislashes are not there anymore and the file opens in Word so I think it should be the issue.
I think the code is wrong here:
String outFile = externalPath + java.io.File.separator + fileName;
should be
if (externalPath=="")
String outFile = externalPath + fileName;
else
String outFile = externalPath + java.io.File.separator + fileName;
I have the below code.
The below source code is from the file x.java. The hi.html is present in the same directory as x.java.
I get a file not found exception even though the file is present. Am I missing something ?
public void sendStaticResource() throws IOException{
byte[] bytes = new byte[1024];
FileInputStream fis = null;
try{
File file = new File("hi.html");
boolean p = file.exists();
int i = fis.available();
fis = new FileInputStream(file);
int ch = fis.read(bytes, 0, 1024);
while(ch!=-1){
output.write(bytes, 0, ch);
ch = fis.read(bytes, 0, 1024);
}
}catch(Exception e){
String errorMessage = "file not found";
output.write(errorMessage.getBytes());
}finally {
if(fis != null){
fis.close();
}
}
}
The directory of the .java file is not necessarily the direction your code runs in! You can check the current working dir of your program by in example:
System.out.println( System.getProperty( "user.dir" ) );
You could use the System.getProperty( "user.dir" ) string to make your relative filename an absolute one! Just prefix it to your filename :)
Take a look at your "user.dir" property.
String curDir = System.getProperty("user.dir");
That's where the program will root its search for files that don't have a complete path.
Catch the FileNotFoundException before catching Exception so as to be sure that is the real Exception type.
Since you don't give an absolute location for a file it searches from your working directory. You can store the absolute path in a property file and use that instead or use System.getProperty("user.dir") to return the directory that you are running the Java app from.
Code to get Key-Value from Property files
private void getPropertyFileValues() {
String currentPath = System.getProperty("user.dir") + System.getProperty("file.separator") + "Loader.properties";
FileInputStream fis = null;
try {
fis = new FileInputStream(currentPath);
} catch (FileNotFoundException ex) {
ex.printStackTrace();
}
Properties props = new Properties();
try {
props.load(fis);
} catch (IOException ex) {
ex.printStackTrace();
}
String filePath= props.getProperty("FILE_PATH");
try {
fis.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
I guess you get a NullPointerException:
FileInputStream fis = null;
then the call:
int i = fis.available();
will result in an NullPointerException as the first non-null assignment to fis is later:
fis = new FileInputStream(file);
File Handling in Java:
Use File class for Representing and manipulating file or folder/directory.
you can use constructor :
ex. File file = new File("path/file_name.txt");
or
File file = new File("Path","file_name");
File representation example:
import java.io.File;
import java.util.Date;
import java.io.*;
import java.util.*;
public class FileRepresentation {
public static void main(String[] args) {
File f =new File("path/file_name.txt");
if(f.exists()){
System.out.println("Name " + f.getName());
System.out.println("Absolute path: " +f.getAbsolutePath());
System.out.println("Is writable " +f.canWrite());
System.out.println("Is readable " + f.canRead());
System.out.println("Is File " + f.isFile());
System.out.println("Is Directory " + f.isDirectory());
System.out.println("Last Modified at " + new Date(f.lastModified()));
System.out.println("Length " + f.length() +"bytes long.");
}//if
}//main
}//class
Write data character by character, into Text file by Java:
use FileWriter Class-
import java.io.FileWriter;
import java.io.PrintWriter;
import java.io.Writer;
public class WriteFile {
public static void main(String[] args) throws Exception{
//File writer takes chars and convert into bytes and write to a file
FileWriter writer = new FileWriter("path/file_name.txt");
//if file not exits then created it, else override data
writer.write('A');
writer.write('E');
writer.write('I');
writer.write('O');
writer.write('U');
writer.close();
System.out.println("Successfully Written");
}
}