- Java – file overwrite in java — user-mapped section open error
- Best Solution
- Related Solutions
- Read all text from a file
- Read lines of text from a file
- Memory utilization
- Character encoding
- Java – user-mapped section open error
- Best Solution
- Related Solutions
- file overwrite in java — user-mapped section open error
- leba-lev
- Comments
- file overwrite in java — user-mapped section open error [duplicate]
- leba-lev
- 1 Answers
- Visionary Software Solutions
- Related questions
- Recent Activity
- Donate For Us
Java – file overwrite in java — user-mapped section open error
The following function in a java program is written with the intent to read from a file and overwrite back to the same file after.
public static void readOverWrite(File dir) throws IOException < for (File f : dir.listFiles()) < String[] data = readFile(f).split("\n"); try (BufferedWriter writer = new BufferedWriter(new FileWriter(f))) < for (int i = 0; i < data.length; i++) < writer.write((data[i]+"\n")); >writer.close(); > > >
The error message on trying to run the program is:
Exception in thread "main" java.io.FileNotFoundException: ..\..\data\AQtxt\APW19980807.0261.tml (The requested operation cannot be performed on a file with a user-mapped section open) at java.io.FileOutputStream.open(Native Method) at java.io.FileOutputStream.(Unknown Source) at java.io.FileOutputStream.(Unknown Source) at java.io.FileWriter.(Unknown Source) at General.SplitCreationDate.splitLine(SplitCreationDate.java:37) at General.SplitCreationDate.main(SplitCreationDate.java:53)
Request help in resolving the error.
protected static String readFile(File fullPath) throws IOException < try(FileInputStream stream = new FileInputStream(fullPath)) < FileChannel fc = stream.getChannel(); MappedByteBuffer bb = fc.map(FileChannel.MapMode.READ_ONLY, 0, fc.size()); stream.close(); return Charset.defaultCharset().decode(bb).toString(); >>
Read in another thread that this is a windows issue and so MappedByteBuffer in the readFile method was the cause of the problem. Re-wrote the readFile method as below. It works!
protected static String readFile(File fullPath) throws IOException < String string = ""; try (BufferedReader in = new BufferedReader(new FileReader(fullPath))) < String str; while ((str = in.readLine()) != null) < string += str + "\n"; >> return string; >
Best Solution
You need to close your file streams after opening them, or they will still be around on your system. This can lead to corruption, and errors like this. Review the Java Learning Tutorials on File I/O. This tutorial also shows the way.
import java.io.*; public class ReadWriteTextFile < /** * Fetch the entire contents of a text file, and return it in a String. * This style of implementation does not throw Exceptions to the caller. * * @param aFile is a file which already exists and can be read. */ static public String getContents(File aFile) < //. checks on aFile are elided StringBuilder contents = new StringBuilder(); try < //use buffering, reading one line at a time //FileReader always assumes default encoding is OK! BufferedReader input = new BufferedReader(new FileReader(aFile)); try < String line = null; //not declared within while loop /* * readLine is a bit quirky : * it returns the content of a line MINUS the newline. * it returns null only for the END of the stream. * it returns an empty String if two newlines appear in a row. */ while (( line = input.readLine()) != null)< contents.append(line); contents.append(System.getProperty("line.separator")); >> finally < input.close(); >> catch (IOException ex) < ex.printStackTrace(); >return contents.toString(); >
Notice the finally block. This ensures that the stream gets closed whether an Exception happens or not. You should use one to close your open streams.
Related Solutions
Java – How to create a Java string from the contents of a file
Read all text from a file
Java 11 added the readString() method to read small files as a String , preserving line terminators:
String content = Files.readString(path, StandardCharsets.US_ASCII);
For versions between Java 7 and 11, here’s a compact, robust idiom, wrapped up in a utility method:
static String readFile(String path, Charset encoding) throws IOException
Read lines of text from a file
Java 7 added a convenience method to read a file as lines of text, represented as a List . This approach is «lossy» because the line separators are stripped from the end of each line.
List lines = Files.readAllLines(Paths.get(path), encoding);
Java 8 added the Files.lines() method to produce a Stream . Again, this method is lossy because line separators are stripped. If an IOException is encountered while reading the file, it is wrapped in an UncheckedIOException , since Stream doesn’t accept lambdas that throw checked exceptions.
try (Stream lines = Files.lines(path, encoding))
This Stream does need a close() call; this is poorly documented on the API, and I suspect many people don’t even notice Stream has a close() method. Be sure to use an ARM-block as shown.
If you are working with a source other than a file, you can use the lines() method in BufferedReader instead.
Memory utilization
The first method, that preserves line breaks, can temporarily require memory several times the size of the file, because for a short time the raw file contents (a byte array), and the decoded characters (each of which is 16 bits even if encoded as 8 bits in the file) reside in memory at once. It is safest to apply to files that you know to be small relative to the available memory.
The second method, reading lines, is usually more memory efficient, because the input byte buffer for decoding doesn’t need to contain the entire file. However, it’s still not suitable for files that are very large relative to available memory.
For reading large files, you need a different design for your program, one that reads a chunk of text from a stream, processes it, and then moves on to the next, reusing the same fixed-sized memory block. Here, «large» depends on the computer specs. Nowadays, this threshold might be many gigabytes of RAM. The third method, using a Stream is one way to do this, if your input «records» happen to be individual lines. (Using the readLine() method of BufferedReader is the procedural equivalent to this approach.)
Character encoding
One thing that is missing from the sample in the original post is the character encoding. There are some special cases where the platform default is what you want, but they are rare, and you should be able justify your choice.
The StandardCharsets class defines some constants for the encodings required of all Java runtimes:
String content = readFile("test.txt", StandardCharsets.UTF_8);
The platform default is available from the Charset class itself:
String content = readFile("test.txt", Charset.defaultCharset());
Note: This answer largely replaces my Java 6 version. The utility of Java 7 safely simplifies the code, and the old answer, which used a mapped byte buffer, prevented the file that was read from being deleted until the mapped buffer was garbage collected. You can view the old version via the «edited» link on this answer.
Java – File to byte[] in Java
From JDK 7 you can use Files.readAllBytes(Path) .
import java.io.File; import java.nio.file.Files; File file; // . (file is initialised). byte[] fileContent = Files.readAllBytes(file.toPath());
Java – user-mapped section open error
When I try to write to the file specified it comes up with the error below. I have tried closing the FileInputStream but I still come up with the same problem.
Here is the relevant code:
Error: C:\Path\Hours Log.csv (The requested operation cannot be performed on a file with a user-mapped section open)
private void writeLog() throws IOException < //set up vars and write directories File yearStatDir = new File("C:\\Path); File yearStatPath = new File(yearStatDir + "\\" + "Hours Log.csv"); String yearStatString = yearStatPath.toString(); //read the files String existingYearLog = readLogFile(yearStatString, yearStatPath); //write the updated file String hoursString = "1"; String dataYear = existingYearLog + hoursString; String folderYear = "Satistics\\Yearly data\\" + yearString; writeFile(dataYear, ".csv", folderYear, "Hours Log"); >
private void writeFile(String data, String fileType, String folder, String fileName) < try< File fileDir = new File("C:\\Path\\" + folder); File filePath = new File(fileDir + "\\"+ fileName + fileType); writeDir(fileDir); // Create file FileWriter fstream = new FileWriter(filePath); try (BufferedWriter out = new BufferedWriter(fstream)) < out.write(data); >>catch (Exception e)/Catch exception if any System.err.println("Error: " + e.getMessage()); > >
private static String readLogFile(String path, File f) throws IOException < if (f.exists())< try (FileInputStream stream = new FileInputStream(new File(path))) < FileChannel fc = stream.getChannel(); MappedByteBuffer bb = fc.map(FileChannel.MapMode.READ_ONLY, 0, fc.size()); /* Instead of using default, pass in a decoder. */ fc.close(); return Charset.defaultCharset().decode(bb).toString(); >> else < return ""; >>
Best Solution
For anyone that comes across this, here is the alternative code that I am using now:
private static String readLogFile(String path) throws IOException < File f = new File(path); if(f.exists()) < FileInputStream fis = new FileInputStream(f); Integer fileLength = (int) (long) f.length(); byte[] b = new byte[fileLength]; int read = 0; while (read < b.length) < read += fis.read(b, read, b.length - read); >String text = new String(b); return text; > else < String text = ""; return text; >>
Related Solutions
Java – What are the differences between a HashMap and a Hashtable in Java
There are several differences between HashMap and Hashtable in Java:
- Hashtable is synchronized, whereas HashMap is not. This makes HashMap better for non-threaded applications, as unsynchronized Objects typically perform better than synchronized ones.
- Hashtable does not allow null keys or values. HashMap allows one null key and any number of null values.
- One of HashMap’s subclasses is LinkedHashMap , so in the event that you’d want predictable iteration order (which is insertion order by default), you could easily swap out the HashMap for a LinkedHashMap . This wouldn’t be as easy if you were using Hashtable .
Since synchronization is not an issue for you, I’d recommend HashMap . If synchronization becomes an issue, you may also look at ConcurrentHashMap .
Java – Is Java “pass-by-reference” or “pass-by-value”
Java is always pass-by-value. Unfortunately, when we deal with objects we are really dealing with object-handles called references which are passed-by-value as well. This terminology and semantics easily confuse many beginners.
public static void main(String[] args) < Dog aDog = new Dog("Max"); Dog oldDog = aDog; // we pass the object to foo foo(aDog); // aDog variable is still pointing to the "Max" dog when foo(. ) returns aDog.getName().equals("Max"); // true aDog.getName().equals("Fifi"); // false aDog == oldDog; // true >public static void foo(Dog d) < d.getName().equals("Max"); // true // change d inside of foo() to point to a new Dog instance "Fifi" d = new Dog("Fifi"); d.getName().equals("Fifi"); // true >
In the example above aDog.getName() will still return «Max» . The value aDog within main is not changed in the function foo with the Dog «Fifi» as the object reference is passed by value. If it were passed by reference, then the aDog.getName() in main would return «Fifi» after the call to foo .
public static void main(String[] args) < Dog aDog = new Dog("Max"); Dog oldDog = aDog; foo(aDog); // when foo(. ) returns, the name of the dog has been changed to "Fifi" aDog.getName().equals("Fifi"); // true // but it is still the same dog: aDog == oldDog; // true >public static void foo(Dog d) < d.getName().equals("Max"); // true // this changes the name of d to be "Fifi" d.setName("Fifi"); >
In the above example, Fifi is the dog’s name after call to foo(aDog) because the object’s name was set inside of foo(. ) . Any operations that foo performs on d are such that, for all practical purposes, they are performed on aDog , but it is not possible to change the value of the variable aDog itself.
For more information on pass by reference and pass by value, consult the following SO answer: https://stackoverflow.com/a/430958/6005228. This explains more thoroughly the semantics and history behind the two and also explains why Java and many other modern languages appear to do both in certain cases.
Related Question
file overwrite in java — user-mapped section open error
You need to close your file streams after opening them, or they will still be around on your system. This can lead to corruption, and errors like this. Review the Java Learning Tutorials on File I/O. This tutorial also shows the way.
import java.io.*; public class ReadWriteTextFile < /** * Fetch the entire contents of a text file, and return it in a String. * This style of implementation does not throw Exceptions to the caller. * * @param aFile is a file which already exists and can be read. */ static public String getContents(File aFile) < //. checks on aFile are elided StringBuilder contents = new StringBuilder(); try < //use buffering, reading one line at a time //FileReader always assumes default encoding is OK! BufferedReader input = new BufferedReader(new FileReader(aFile)); try < String line = null; //not declared within while loop /* * readLine is a bit quirky : * it returns the content of a line MINUS the newline. * it returns null only for the END of the stream. * it returns an empty String if two newlines appear in a row. */ while (( line = input.readLine()) != null)< contents.append(line); contents.append(System.getProperty("line.separator")); >> finally < input.close(); >> catch (IOException ex) < ex.printStackTrace(); >return contents.toString(); >
Notice the finally block. This ensures that the stream gets closed whether an Exception happens or not. You should use one to close your open streams.
leba-lev
Comments
The following function in a java program is written with the intent to read from a file and overwrite back to the same file after.
public static void readOverWrite(File dir) throws IOException < for (File f : dir.listFiles()) < String[] data = readFile(f).split("\n"); try (BufferedWriter writer = new BufferedWriter(new FileWriter(f))) < for (int i = 0; i < data.length; i++) < writer.write((data[i]+"\n")); >writer.close(); > > >
Exception in thread "main" java.io.FileNotFoundException: ..\..\data\AQtxt\APW19980807.0261.tml (The requested operation cannot be performed on a file with a user-mapped section open) at java.io.FileOutputStream.open(Native Method) at java.io.FileOutputStream.(Unknown Source) at java.io.FileOutputStream.(Unknown Source) at java.io.FileWriter.(Unknown Source) at General.SplitCreationDate.splitLine(SplitCreationDate.java:37) at General.SplitCreationDate.main(SplitCreationDate.java:53)
protected static String readFile(File fullPath) throws IOException < try(FileInputStream stream = new FileInputStream(fullPath)) < FileChannel fc = stream.getChannel(); MappedByteBuffer bb = fc.map(FileChannel.MapMode.READ_ONLY, 0, fc.size()); stream.close(); return Charset.defaultCharset().decode(bb).toString(); >>
Read in another thread that this is a windows issue and so MappedByteBuffer in the readFile method was the cause of the problem. Re-wrote the readFile method as below. It works!
protected static String readFile(File fullPath) throws IOException < String string = ""; try (BufferedReader in = new BufferedReader(new FileReader(fullPath))) < String str; while ((str = in.readLine()) != null) < string += str + "\n"; >> return string; >
file overwrite in java — user-mapped section open error [duplicate]
The following function in a java program is written with the intent to read from a file and overwrite back to the same file after.
public static void readOverWrite(File dir) throws IOException < for (File f : dir.listFiles()) < String[] data = readFile(f).split("\n"); try (BufferedWriter writer = new BufferedWriter(new FileWriter(f))) < for (int i = 0; i < data.length; i++) < writer.write((data[i]+"\n")); >writer.close(); > > >
The error message on trying to run the program is:
Exception in thread "main" java.io.FileNotFoundException: ..\..\data\AQtxt\APW19980807.0261.tml (The requested operation cannot be performed on a file with a user-mapped section open) at java.io.FileOutputStream.open(Native Method) at java.io.FileOutputStream.(Unknown Source) at java.io.FileOutputStream.(Unknown Source) at java.io.FileWriter.(Unknown Source) at General.SplitCreationDate.splitLine(SplitCreationDate.java:37) at General.SplitCreationDate.main(SplitCreationDate.java:53)
Request help in resolving the error.
protected static String readFile(File fullPath) throws IOException < try(FileInputStream stream = new FileInputStream(fullPath)) < FileChannel fc = stream.getChannel(); MappedByteBuffer bb = fc.map(FileChannel.MapMode.READ_ONLY, 0, fc.size()); stream.close(); return Charset.defaultCharset().decode(bb).toString(); >>
Read in another thread that this is a windows issue and so MappedByteBuffer in the readFile method was the cause of the problem. Re-wrote the readFile method as below. It works!
protected static String readFile(File fullPath) throws IOException < String string = ""; try (BufferedReader in = new BufferedReader(new FileReader(fullPath))) < String str; while ((str = in.readLine()) != null) < string += str + "\n"; >> return string; >
leba-lev
1 Answers
You need to close your file streams after opening them, or they will still be around on your system. This can lead to corruption, and errors like this. Review the Java Learning Tutorials on File I/O. This tutorial also shows the way.
import java.io.*; public class ReadWriteTextFile < /** * Fetch the entire contents of a text file, and return it in a String. * This style of implementation does not throw Exceptions to the caller. * * @param aFile is a file which already exists and can be read. */ static public String getContents(File aFile) < //. checks on aFile are elided StringBuilder contents = new StringBuilder(); try < //use buffering, reading one line at a time //FileReader always assumes default encoding is OK! BufferedReader input = new BufferedReader(new FileReader(aFile)); try < String line = null; //not declared within while loop /* * readLine is a bit quirky : * it returns the content of a line MINUS the newline. * it returns null only for the END of the stream. * it returns an empty String if two newlines appear in a row. */ while (( line = input.readLine()) != null)< contents.append(line); contents.append(System.getProperty("line.separator")); >> finally < input.close(); >> catch (IOException ex) < ex.printStackTrace(); >return contents.toString(); >
Notice the finally block. This ensures that the stream gets closed whether an Exception happens or not. You should use one to close your open streams.
Visionary Software Solutions
Related questions
Recent Activity
Donate For Us
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!