I'm trying to code something to copy the content of one file into another existent file without deleting its content.
The problem is that, that other existent file is created inside a loop and I don't know how to do it to save it and then using it in another method.
Here's the loop:
if (line.startsWith("tipo1.")) {
FileWriter fw = new FileWriter(name + ".txt");
char[] vector = name.toCharArray();
char[] vector2 = address.toCharArray();
int index = 0;
while (index < vector.length) {
fw.write(vector[index]);
index++;
}
index = 0;
while (index < vector2.length) {
fw.write(vector2[index]);
index++;
}
fw.close();
}
And what I want to do is to save (name + ".txt") file and then adding the content of another file into it.
I'm sure it's not so difficult to do, but I'm really stuck.
You already have two separate pieces of information being written into the file: the name (as vector) and the address (as vector2). Why not just read in your other file as, say, vector3 and add one more while loop?
If you want this done the easy way then use Apache IO, and use: File ip = new File("input.txt"); File op = new File("output.txt"); FileUtils.copyFile(ip, op);
FileReader ip = new FileReader("input.txt");
FileWriter op = new FileWriter("output.txt", true);
int c;
while (true) {
c = ip.read();
if (c == -1) {
break;
}
op.write((char)c);
}
ip.close();
op.close();
Related
I'm working a transfer file program and my program is working but I'm having a problem because when I select multiple files and put it on a textbox the source directory can't read what is on the textbox
this is my code
Opening file/files
btnSearchFile.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
FileDialog fd = new FileDialog(shell, SWT.MULTI);
Collection files = new ArrayList();
String firstFile = fd.open();
if (firstFile != null) {
String[] selectedFiles = fd.getFileNames();
File file = new File(firstFile);
for (int ii = 0; ii < selectedFiles.length; ii++ )
{
if (file.isFile())
{
displayFiles(new String[] { file.toString()});
}
else
displayFiles(file.list());
}
}
}
});
Displaying Files on textbox
public void displayFiles(String[] files) {
for (int i = 0; files != null && i < files.length; i++) {
txtSource.append(files[i]);
txtSource.setEditable(false);
}
}
Copy Files
public static void copyFile(File src, File dest) throws IOException
{
InputStream oInStream = new FileInputStream(src);
OutputStream oOutStream = new FileOutputStream(dest);
// Transfer bytes from in to out
byte[] oBytes = new byte[1024];
int nLength;
BufferedInputStream oBuffInputStream = new BufferedInputStream( oInStream );
while ((nLength = oBuffInputStream.read(oBytes)) > 0)
{
oOutStream.write(oBytes, 0, nLength);
}
oInStream.close();
oOutStream.close();
}
PS: One file is okay but if multiple files are selected and put on the textbox the source directory can't be found
In order to be completely helpful, we could really use some more detail (specific exceptions, a complete MCVE, which SWT widgets are used, etc.).
That said, I think you've provided enough to see that there are some issues with your code:
For starters, when you have multiple files selected, you're displaying the same file name (the name of the first one) over and over. Perhaps this is intentional, but worth mentioning:
String[] selectedFiles = fd.getFileNames();
File file = new File(firstFile);
for (int ii = 0; ii < selectedFiles.length; ii++ )
{
// You've used a FileDialog, so this should always be true
if (file.isFile())
{
// Will always be the first file
displayFiles(new String[] { file.toString()});
}
else
displayFiles(file.list());
}
Based on the context, I'm assuming txtSource is a Text widget. With that in mind, if we look at your displayFiles() method, you have the following:
txtSource.append(files[i]);
When you call displayFiles() repeatedly, you will be tacking on a file name after all the others, effectively building one long String which is the combination of all file names. When you go to copy the files listed, splitting that String back into valid file paths will be tricky.
My guess is that when you say:
"the source directory can't be found"
...you're just grabbing the content of txtSource. Something like this:
new File(txtSource.getText());
"...One file is okay..."
That will certainly work if there's only one file name in the Text object, but if there are multiple names it will result in a non-existent File.
For example, if you've selected two files:
C:\Users\me\FileA
C:\Users\me\FileB
Your txtSource would display C:\Users\me\FileAC:\Users\me\FileB. And the path C:\Users\me\FileAC:\Users\me\FileB most likely does not exist.
In that case, new File(txtSource.getText()).exists() would return false, and using that File in the constructor for FileInputStream (inside copyFile()) would result in a FileNotFoundException.
In short, just make sure that when you make your call to copyFile() and create the source File object that you're giving the path that you think you are, and not the concatenation of all files selected.
(Hello world level tester here)
I've got a java application to delete a bunch of files post tests to keep everything clean, however the issue is I can't seem to get it to work, this is my first time touching on an array and it's a slightly more complex one than the ones they show in the tutorials, any assistance would be greatly appreciated.
String[] fileArray;
fileArray = new String[8];
fileArray[0] = "/Downloads/file1.csv";
fileArray[1] = "/Downloads/file2.csv";
fileArray[2] = "/Downloads/file3.csv";
fileArray[3] = "/Downloads/file4.csv";
fileArray[4] = "/Downloads/file5.csv";
fileArray[5] = "/Downloads/file6.csv";
fileArray[6] = "/Downloads/file7.csv";
fileArray[7] = "/Downloads/file8.csv";
String home = System.getProperty("user.home");
File filePath = new File(home+fileArray);
System.out.println(filePath);
for (String count: fileArray) {
if (filePath.exists()) {
filePath.delete();
System.out.println("Deleted");
}
else
{
System.out.println("failed");
Assert.fail();
}
System.out.println(count);
}
You should concat new file path for every element in an array, so need to put work with a file in for body. So in every iteration, you get in variable filePath next element of an array and then you need to concat this variable to base path home + filePath. Now you are looking at needed file, you can create file object and work with it.
String[] fileArray;
fileArray = new String[8];
fileArray[0] = "/Downloads/file1.csv";
fileArray[1] = "/Downloads/file2.csv";
fileArray[2] = "/Downloads/file3.csv";
fileArray[3] = "/Downloads/file4.csv";
fileArray[4] = "/Downloads/file5.csv";
fileArray[5] = "/Downloads/file6.csv";
fileArray[6] = "/Downloads/file7.csv";
fileArray[7] = "/Downloads/file8.csv";
String home = System.getProperty("user.home");
for (String filePath: fileArray) {
File file = new File(home + filePath);
System.out.println(filePath);
if (file.exists()) {
file.delete();
System.out.println("Deleted");
} else {
System.out.println("failed");
Assert.fail();
}
}
Seem like you expect that in variable count you will see a number of iterated files. In this case, it does not work like this. Such form of for acting like this: for (String arrayElement : arrayToWorkWith) - mean that on every iteration in variable arrayElement will be put next element from array arrayToWorkWith. If you need to count number of element during iterations you can introduce separate variable and increment it or use another form of for cycle - for (int i = 0; i < fileArray.length; i++).
try it this way
String[] fileArray;
fileArray = new String[8];
fileArray[0] = "/Downloads/file1.csv";
fileArray[1] = "/Downloads/file2.csv";
fileArray[2] = "/Downloads/file3.csv";
fileArray[3] = "/Downloads/file4.csv";
fileArray[4] = "/Downloads/file5.csv";
fileArray[5] = "/Downloads/file6.csv";
fileArray[6] = "/Downloads/file7.csv";
fileArray[7] = "/Downloads/file8.csv";
String home = System.getProperty("user.home");
//File filePath = new File(home+fileArray); thats wrong here and will give you a invalid file anyway as you concatenating a string with an object
for (String file: fileArray) {
File filePath = new File(home+file); //here you need to define the file
if (filePath.exists()) {
filePath.delete();
System.out.println("Deleted");
}
else
{
System.out.println("failed");
Assert.fail();
}
System.out.println(file);
}
One class of my GUI has a variable for the file name. I want to pass this to another class so that I can process a file without having to hard code the file's name every time. The program compiles fine but I can't seem to run it correctly.
public void run() {
WordsCounter2 fileName = new WordsCounter2();
essayName = fileName.getFileList();
File f = new File(essayName);
//other code
WordsCounter2 is the class that houses the variable fileName, I'm calling it from this class and assigning it as the file's name, but this doesn't work. Could someone help?
if (rVal == JFileChooser.APPROVE_OPTION) {
File[] selectedFile = fileChooser.getSelectedFiles();
fileList = "nothing";
if (selectedFile.length > 0)
fileList = selectedFile[0].getName();
for (int i = 1; i < selectedFile.length; i++) {
fileList += ", " + selectedFile[i].getName();
}
statusBar.setText("You chose " + fileList);
}
else {
statusBar.setText("You didn't choose a file.");
}
fileList isn't empty because I have a label on the GUI that lists whatever file I chose.
Here's my new edit: now the exception occurs at the last line with the scanner and throws a NPE. Can you help?
public void run() {
WordsCounter2 pathNamesList = new WordsCounter2();
essayName = pathNamesList.getPathNamesList();
essayTitle = new String[essayName.size()];
essayTitle = essayName.toArray(essayTitle);
for (int i = 0; i < essayTitle.length; i++) {
f = new File(essayTitle[i]);
}
try {
Scanner scanner = new Scanner(f);
Your code is failing because File will not accept comma separated file names, in fact, it needs a single file path to create the file in the mentioned path. See here: https://docs.oracle.com/javase/7/docs/api/java/io/File.html
You'll have to get complete paths in an array and put the file creation statement as follows:
File f;
for (int i=0; i<fileList.length; i++)
f = new File(fileList[i]);
where fileList is a String array holding the list of pathnames.
In case you're trying to write some content to these files as well, this should be helpful: Trying to Write Multiple Files at Once - Java
So here is my problem (I read the other answers, but didn't quite get it).
In a group of 4, we have created a game in Java as a University Project. Part of this is creating a *.jar File via Ant. There is several GameBoards saved in GameBoardx.txt Data where x is the number. We want to randomly select one of those. Therefore, every time a GameBoard is loaded, the files in the GameBoard directory are counted in order to generate a random number in the correct range. Our code works perfectly fine when running it from Eclipse. It fails to run from the *.jar File and exits with a NullPointerException.
int number = 0;
int fileCount = new File(new File("").getAbsolutePath()+"/GameBoards/").listFiles().length;
Random rand = new Random();
number = rand.nextInt(fileCount);
These Files are read later on using this:
static String fileName = new File("").getAbsolutePath();
static String line = null;
boolean verticalObstacles[][] = new boolean[16][17];
int currentLine = 1;
try {
FileReader fileReader = new FileReader(fileName+"/GameBoards/Board"+boardNumber+".txt");
BufferedReader bufferedReader = new BufferedReader(fileReader);
while ((line = bufferedReader.readLine()) != null){
if (currentLine <17){
for (int i=0; i<17; i++){
if (line.charAt(i) == '1'){
verticalObstacles[currentLine-1][i] = true;
} else {
verticalObstacles[currentLine-1][i] = false;
}
}
}
currentLine ++;
}
bufferedReader.close();
The rest of the code works with the *.jar File and the *.txt Files are included in it.
The solutions I found were not good for us, because the code has to work with the *.jar File as well as just starting it from Eclipse to pass the test.
What's the solution here to make in work in both?
Problem here is you can not read content of a Jar using File, you shall use java.nio classes to deal with this.
First of all you can read/get count of files from Jar/normal folder by using FileSystem, Path and FileVisitor classes:
Following code will work for both jar as well as IDE
ClassLoader sysClassLoader = ClassLoader.getSystemClassLoader();
URI uri = sysClassLoader.getResource("GameBoards").toURI();
Path gameBoardPath = null;
if (uri.getScheme().equals("jar")) {
FileSystem fileSystem = FileSystems.newFileSystem(uri,
Collections.<String, Object> emptyMap());
gameBoardPath = fileSystem.getPath("/GameBoards");
} else {
gameBoardPath = Paths.get(uri);
}
PathVisitor pathVistor = new PathVisitor();
Files.walkFileTree(gameBoardPath, pathVistor);
System.out.println(pathVistor.getFileCount());
Following is the code for PathVisitor class
class PathVisitor extends SimpleFileVisitor<Path> {
private int fileCount = 0;
#Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs)
throws IOException {
fileCount++;
return FileVisitResult.CONTINUE;
}
public int getFileCount() {
return fileCount;
}
}
And then you shall read content of specific file by using ClassLoader#getResourceAsStream
// ADD your random file picking logic here based on file Count to get boardNum
int boardNum = 1;
InputStream is = sysClassLoader.getResourceAsStream("GameBoards/Board" + boardNum + ".txt");
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
String line = null;
while((line=reader.readLine())!=null) {
System.out.println(line);
}
Hope this resolves your concerns and helps you in right direction.
I have the following:
Folder that contains many files (about 300000), named "AllFilesFolder"
list of names, named "namesList"
An empty folder, named "filteredFolder"
I want to filter the folder "AllFilesFolder", by moving any file that contins any of the names in the list to the empty folder "filteredFolder".
I have approche this problem by the following code:
public static void doIt(List<String>namesList, String AllFilesFolder, String filteredFolder) throws FileNotFoundException {
// here we put all the files in the original folder in List variable name "filesList"
File[] filesList = new File(AllFilesFolder).listFiles();
// went throught the files one by one
for (File f : filesList) {
try {
FileReader fr = new FileReader(f);
BufferedReader reader = new BufferedReader(fr);
String line = "";
//this varibale used to test withir the files contins names or not
//we set it to false.
boolean goodDoc = false;
//go through the file line by line to chick the names (I wounder if there are a simbler whay)
while ((line = reader.readLine()) != null) {
for(String name:namesList){
if ( line.contains(name)) {
goodDoc = true;
}
}
}
reader.close();
// if this file contains the name we put this file into the other folder "filteredFolder"
if (goodDoc) {
InputStream inputStream = new FileInputStream(f);
OutputStream out = new FileOutputStream(new File(filteredFolder + f.getName()));
int read = 0;
byte[] bytes = new byte[4096];
while ((read = inputStream.read(bytes)) != -1) {
out.write(bytes, 0, read);
}
inputStream.close();
out.flush();
out.close();
}
} catch (Exception e) {
System.err.println(e);
}
}
}
By doing this I have two problems that I need your advice to solve:
I am reading each file twice, one time to search and the other to put it into the other folder.
When searching namesList I have for loop to takes the names one by one, Is there a way to search the list one time (without loop).
Many thanks in advance
I am reading each file twice, one time to search and the other to put it into the other folder.
Using NIO improves the copy performance. Here is the code example. If you can use Java 7 then you can use Files.copy()
When searching namesList I have for loop to takes the names one by one, Is there a way to search the list one time (without loop).
Use HashSet to store the names and use contains() method. It is a O(1) operation. Or another suggestion is to use Scanner.findWithinHorizon(pattern, horizon)