Hello i am trying to manipulate a file(copying temp to orig.) but it seems that there is a problem (access is denied) whenever i try to open transaction_sales.dat file for the second time. What should I do? :(((
public static void writeFile() {
Path file = null;
Path file2 = null;
OutputStream output = null;
BufferedWriter writer = null;
InputStream input = null;
BufferedReader reader = null;
String[] strReaderAssign = new String[10000]; // for reading files
String strReader = null;
int strike = 0; // counter
try { // UNFINISHED
file = Paths.get("transaction_sales.dat");
output = new BufferedOutputStream(Files.newOutputStream(file, CREATE));
writer = new BufferedWriter(new OutputStreamWriter(output));
input = new BufferedInputStream(Files.newInputStream(file));
reader = new BufferedReader(new InputStreamReader(input));
if(reader.readLine() == null) { // if file is empty
writer.write(strHolder, 0, strHolder.length()); // writes to file
writer.close(); // closes file
reader.close(); // closes read file
}
else { // write to temporary file
file = Paths.get("transaction_sales.dat");
file2 = Paths.get("transaction_sales_temp.dat"); // temporary file
output = new BufferedOutputStream(Files.newOutputStream(file2));
writer = new BufferedWriter(new OutputStreamWriter(output));
writer.write((strHolder), 0, strHolder.length()); // writes to temp file
for(int i = 0; i < 10; i++) {
writer.newLine(); // writes new line to file 10x
}
writer.close(); // closes file
try {
file = Paths.get("transaction_sales.dat"); // re-reads updated data in a file
input = new BufferedInputStream(Files.newInputStream(file));
reader = new BufferedReader(new InputStreamReader(input));
while((strReader = reader.readLine()) != null) {
strReaderAssign[strike] = strReader; // assigns to array
strike++; // increment
}
strike = 0; // resets value
reader.close(); // closes file
// appends file
output = new BufferedOutputStream(Files.newOutputStream(file2, APPEND));
writer = new BufferedWriter(new OutputStreamWriter(output));
for(int j = 0; (strReaderAssign[j] != null); j++) {
writer.write(strReaderAssign[j]);
writer.newLine();
}
// resets value
for(int j = 0; j < strReaderAssign.length; j++) {
strReaderAssign[j] = null;
}
writer.close(); // closes file
file = Paths.get("transaction_sales.dat");
file2 = Paths.get("transaction_sales_temp.dat");
Files.copy(file2, file, REPLACE_EXISTING);
Files.delete(file);
}
catch(IOException d) {
System.out.println(d.getMessage());
}
}
}
catch(Exception e) {
System.out.println(e.getMessage());
}
}
Related
I'm just a beginner and got the following task:
Write first 100 positive and 100 negative integers to the file, listing them separated by a space.
Then read this file and put the read numbers into 2 files: positive_numbers and negative_numbers.
public static void main(String[] args) throws IOException {
File numbers = new File("C:\\numbers.txt");
File positivNumbers = new File("C:\\positivnumbers.txt");
File negativNumbers = new File("C:\\negativnumbers.txt");
try (
BufferedWriter wr = new BufferedWriter(new FileWriter(numbers));
BufferedReader rd = new BufferedReader(new FileReader(numbers));
BufferedWriter brnegativ = new BufferedWriter(new FileWriter(negativNumbers));
BufferedWriter brpositiv = new BufferedWriter(new FileWriter(positivNumbers));) {
if (numbers.exists()) {
for (int i = 0; i <= 100; i++) {
wr.write(String.valueOf((i) + " "));
}
for (int a = -1; a >= -100; a--) {
wr.write(((a) + " "));
}
String line = rd.readLine();
while (line != null) {
brpositiv.write(line);
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
I could write numbers as a String to file "numbers". But I cannot read and write them in "positiv" output file.The file is empty. Where is my mistake?
After the writing you have to close wr so all data in memory gets flushed to the file. AFTER the close you can reopen it for read. So in your code you open rd too soon.
try (BufferedWriter wr = new BufferedWriter(new FileWriter(numbers));) {
for (int i = 0; i <= 100; i++) {
wr.write(String.valueOf((i) + " "));
}
for (int a = -1; a >= -100; a--) {
wr.write(((a) + " "));
}
} catch (IOException e) {
e.printStackTrace();
}
// file is closed by try-with-resources ...
// ... so now we can open it for read:
try (BufferedReader rd = new BufferedReader(new FileReader(numbers));
BufferedWriter brnegativ = new BufferedWriter(new FileWriter(negativNumbers));
BufferedWriter brpositiv = new BufferedWriter(new FileWriter(positivNumbers));) {
String line = rd.readLine();
while (line != null) {
brpositiv.write(line);
// TODO : split logic
}
} catch (IOException e) {
e.printStackTrace();
}
The code is like this:
public class TxtToCsvConverter{
private static final String DATA_FILE_NAME = "/Desktop/ml-1m/movies.dat";
public static void main(String[] args) {
StringBuilder bulider = new StringBuilder();
try{
// Open the file
FileInputStream fileInputStream = new FileInputStream(DATA_FILE_NAME);
// Create a new csv file to store your data
PrintWriter writer = new PrintWriter(new File("result.csv"));
DataInputStream dataInputStream = new DataInputStream(fileInputStream);
BufferedReader reader = new BufferedReader(new InputStreamReader(dataInputStream));
String strLine;
// Read file line by line
while ((strLine = reader.readLine()) != null) {
String[] stringArray = strLine.split("::");
for (int i = 0; i < stringArray.length; i++) {
bulider.append(stringArray[i]);
bulider.append(",");
}
bulider.append("\n");
}
// Close the input stream
dataInputStream.close();
// Write builder into file
writer.write(bulider.toString());
// Save the file
writer.close();
}catch (Exception e) {
// Catch exception if any
System.err.println("Error: " + e.getMessage());
}
}
}
And it appears to come out a error says
Could not find or load main class TxtToCsvConverter.data_preprocess"
I couldn't find the reason. Please help
Hi I want to write an array to a file I can do this except I want to write the first 50 objects of the array on first line then move to the next line and write another 50 numbers and then the next line and so on.
at the moment I have this:
if (pause.save) {
Formatter f;
FileWriter fw;
PrintWriter pw = null;
File f2 = new File("docs/save.txt");
FileReader r;
BufferedReader r1;
try{
//f = new Formatter("docs/save.txt");
f2.createNewFile();
fw = new FileWriter(f2);
pw = new PrintWriter(fw);
pw.println(mapwidth);
pw.println(mapheight);
for(int i = 0; i < overview.s.toArray().length; i ++){
pw.println(overview.s.get(i).getID());
}
}catch(IOException e){
e.printStackTrace();
System.out.println("ERROR!!!");
}finally{
pw.close();
}
}
I have been trying to do this for ages but cant figure it out.
You can do this in following way:-
for(int i = 0; i < overview.s.toArray().length; i ++){
pw.println(overview.s.get(i).getID());
if(i!=0&&i%50==0)
//newline here
}
Just do:
if (pause.save) {
Formatter f;
FileWriter fw;
PrintWriter pw = null;
File f2 = new File("docs/save.txt");
FileReader r;
BufferedReader r1;
try{
//f = new Formatter("docs/save.txt");
f2.createNewFile();
fw = new FileWriter(f2);
pw = new PrintWriter(fw);
pw.println(mapwidth);
pw.println(mapheight);
for(int i = 0; i < overview.s.toArray().length; i ++){
pw.print(overview.s.get(i).getID());
if ((i + 1) % 50 == 0) {
pw.println();
}
}
}catch(IOException e){
e.printStackTrace();
System.out.println("ERROR!!!");
}finally{
pw.close();
}
}
How can i wright in the beggining of the first file infomation which contains in second file, so that they merge each other?? please help, thanks.
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
FileInputStream fileReader = new FileInputStream(reader.readLine());
FileOutputStream fileWriter = new FileOutputStream(reader.readLine(), true);
while (fileReader.available() > 0) {
int data = fileReader.read();
fileWriter.write(data);
}
fileReader.close();
fileWriter.close();
reader.close();
This can be done in pure Java...
It reads the second file and appends to the first file.
Keep in mind, that this will not work for large files, since it saves all of fileA content into memory.
Scanner reader = new Scanner(System.in);
System.out.println("Enter the first file path");
String fileA = reader.next();
System.out.println("Enter the second file path");
String fileB = reader.next();
try {
// Read from and cache fileA
StringBuilder cache = new StringBuilder();
BufferedReader readerA = new BufferedReader(new FileReader(new File(fileA)));
String line = null;
while((line = readerA.readLine()) != null) {
cache.append(line);cache.append("\n");
}
readerA.close();
// Read from fileB and overwrite to fileA
FileWriter writerB = new FileWriter(new File(fileA));
BufferedReader readerB = new BufferedReader(new FileReader(new File(fileB)));
line = null;
while((line = readerB.readLine()) != null) {
writerB.write(line);writerB.write("\n");
}
writerB.close();
readerB.close();
// Append original fileA content back into fileA
FileWriter writerA = new FileWriter(new File(fileA), true);
writerA.write(cache.toString());
writerA.close();
} catch (Exception e) {
e.printStackTrace();
}
Simply use
org.apache.commons.io.FileUtils.copyFile(srcFile, destFile);
//rename the file names if needed
OR you can use SequenceInputStream to create a sequence of multiple input stream.
Sample code:
File srcFile = new File("resources/abc.txt");
File destFile = new File("resources/xyz.txt");
File temp = new File("resources/temp.txt");
try {
FileInputStream fileInputStream1 = new FileInputStream(srcFile);
FileInputStream fileInputStream2 = new FileInputStream(destFile);
SequenceInputStream inputStream = new SequenceInputStream(fileInputStream1,
fileInputStream2);
FileOutputStream outputStream = new FileOutputStream(temp);
byte[] buffer = new byte[1024];
int read = -1;
while ((read = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, read);
}
inputStream.close();
outputStream.close();
fileInputStream1.close();
fileInputStream2.close();
// here you can rename the temp file or delete a source file if needed
} catch (IOException e) {
e.printStackTrace();
}
I have a dialog using JFileChooser. When I save a file by FileOutputStream, I want to save it as file.txt in the path which the user want. But it always saves in c:/user/Document.
Here is the code:
DownLoadDialog downloadDialog = new DownLoadDialog();
int result = downloadDialog.showSaveDialog(queryPanel);
if (result == downloadDialog.APPROVE_OPTION) {
File file = downloadDialog.getSelectedFile();
//String parth =file.getPath();
//System.out.println(parth);
//if(file.exists()) {
//int response = JOptionPane.showConfirmDialog (null,
// "Overwrite existing file?","Confirm Overwrite",
// JOptionPane.OK_CANCEL_OPTION,JOptionPane.QUESTION_MESSAGE);
//if(response == JOptionPane.OK_OPTION) {}
//} else {
if (resultGoogleSearch > 0) {
{
String parth = new File(downloadDialog.getSelectedFile().
getAbsolutePath().concat(".txt")).toString();
System.out.println(parth);
for (int i = 0; i < resultGoogleSearch; i++) {
String[] temp = googleSearchResult.get(i).split("<br>");
//String resultURL = temp[0];
//File dir = downloadDialog.getCurrentDirectory();
try {
FileOutputStream googleReuslt = new FileOutputStream(
downloadDialog.getSelectedFile().getAbsolutePath()
+ ".txt");
OutputStreamWriter writer = new
OutputStreamWriter(googleReuslt);
BufferedWriter buffer = new BufferedWriter(writer);
writer.write(temp[0]);
writer.close();
buffer.close();
} catch (FileNotFoundException fEx) {
} catch (IOException ioEx) {
}
}
}
JOptionPane.showMessageDialog(IDRSApplication.idrsJFrame,
IDRSResourceBundle.res.getString("successful"));
}
The problem is here: why can't I set path for new file?
FileOutputStream googleReuslt = new FileOutputStream(
downloadDialog.getSelectedFile().getAbsolutePath() + ".txt");
OutputStreamWriter writer = new OutputStreamWriter(googleReuslt);
BufferedWriter buffer = new BufferedWriter(writer);
writer.write(temp[0]);
writer.close();
buffer.close();
The code you provided works as you would expect. (At least under linux.)
I suggest you do a SSCCE and update your question.