View | Details | Raw Unified | Return to bug 509247
Collapse All | Expand All

(-)a/org.eclipse.jdt.text.tests/src/org/eclipse/jdt/text/tests/contentassist/CodeCompletionTest.java (-3 / +1 lines)
Lines 127-140 Link Here
127
127
128
		System.out.print("file contents: |");
128
		System.out.print("file contents: |");
129
		File file= cu.getResource().getLocation().toFile();
129
		File file= cu.getResource().getLocation().toFile();
130
		try {
130
		try (BufferedReader reader= new BufferedReader(new FileReader(file))) {
131
			BufferedReader reader= new BufferedReader(new FileReader(file));
132
			String line;
131
			String line;
133
			while ((line= reader.readLine()) != null) {
132
			while ((line= reader.readLine()) != null) {
134
				System.out.println(line);
133
				System.out.println(line);
135
			}
134
			}
136
			System.out.println("|");
135
			System.out.println("|");
137
			reader.close();
138
		} catch (FileNotFoundException e1) {
136
		} catch (FileNotFoundException e1) {
139
			e1.printStackTrace();
137
			e1.printStackTrace();
140
		} catch (IOException e1) {
138
		} catch (IOException e1) {
(-)a/org.eclipse.jdt.text.tests/src/org/eclipse/jdt/text/tests/performance/FileTool.java (-71 / +21 lines)
Lines 50-89 Link Here
50
50
51
		Enumeration<? extends ZipEntry> entries = zipFile.entries();
51
		Enumeration<? extends ZipEntry> entries = zipFile.entries();
52
52
53
		try {
53
		while(entries.hasMoreElements()){
54
			while(entries.hasMoreElements()){
54
			ZipEntry entry = entries.nextElement();
55
				ZipEntry entry = entries.nextElement();
55
			if(entry.isDirectory()){
56
				if(entry.isDirectory()){
56
				continue;
57
					continue;
58
				}
59
				String entryName = entry.getName();
60
				File file = new File(dstDir, changeSeparator(entryName, '/', File.separatorChar));
61
				file.getParentFile().mkdirs();
62
				InputStream src = null;
63
				OutputStream dst = null;
64
				try {
65
					src = zipFile.getInputStream(entry);
66
					dst = new FileOutputStream(file);
67
					transferData(src, dst);
68
				} finally {
69
					if(dst != null){
70
						try {
71
							dst.close();
72
						} catch(IOException e){
73
						}
74
					}
75
					if(src != null){
76
						try {
77
							src.close();
78
						} catch(IOException e){
79
						}
80
					}
81
				}
82
			}
57
			}
83
		} finally {
58
			String entryName = entry.getName();
84
			try {
59
			File file = new File(dstDir, changeSeparator(entryName, '/', File.separatorChar));
85
				zipFile.close();
60
			file.getParentFile().mkdirs();
86
			} catch(IOException e){
61
			try (InputStream src = zipFile.getInputStream(entry);
62
					OutputStream dst = new FileOutputStream(file)) {
63
				transferData(src, dst);
87
			}
64
			}
88
		}
65
		}
89
	}
66
	}
Lines 112-136 Link Here
112
	 */
89
	 */
113
	public static void transferData(File source, File destination) throws IOException {
90
	public static void transferData(File source, File destination) throws IOException {
114
		destination.getParentFile().mkdirs();
91
		destination.getParentFile().mkdirs();
115
		InputStream is = null;
92
		try (InputStream is = new FileInputStream(source);
116
		OutputStream os = null;
93
				OutputStream os = new FileOutputStream(destination)) {
117
		try {
118
			is = new FileInputStream(source);
119
			os = new FileOutputStream(destination);
120
			transferData(is, os);
94
			transferData(is, os);
121
		} finally {
122
			if(os != null){
123
				try {
124
					os.close();
125
				} catch(IOException e){
126
				}
127
			}
128
			if(is != null){
129
				try {
130
					is.close();
131
				} catch(IOException e){
132
				}
133
			}
134
		}
95
		}
135
	}
96
	}
136
97
Lines 182-217 Link Here
182
	}
143
	}
183
144
184
	public static StringBuffer read(String fileName) throws IOException {
145
	public static StringBuffer read(String fileName) throws IOException {
185
		return read(new FileReader(fileName));
146
		try (Reader reader = new FileReader(fileName)) {
147
			return read(reader);
148
		}
186
	}
149
	}
187
150
188
	public static StringBuffer read(Reader reader) throws IOException {
151
	public static StringBuffer read(Reader reader) throws IOException {
189
		StringBuffer s= new StringBuffer();
152
		StringBuffer s= new StringBuffer();
190
		try {
153
		char[] buffer= new char[8196];
191
			char[] buffer= new char[8196];
154
		int chars= reader.read(buffer);
192
			int chars= reader.read(buffer);
155
		while (chars != -1) {
193
			while (chars != -1) {
156
			s.append(buffer, 0, chars);
194
				s.append(buffer, 0, chars);
157
			chars= reader.read(buffer);
195
				chars= reader.read(buffer);
196
			}
197
		} finally {
198
			try {
199
				reader.close();
200
			} catch (IOException e) {
201
			}
202
		}
158
		}
203
		return s;
159
		return s;
204
	}
160
	}
205
161
206
	public static void write(String fileName, StringBuffer content) throws IOException {
162
	public static void write(String fileName, StringBuffer content) throws IOException {
207
		Writer writer= new FileWriter(fileName);
163
		try (Writer writer= new FileWriter(fileName)) {
208
		try {
209
			writer.write(content.toString());
164
			writer.write(content.toString());
210
		} finally {
211
			try {
212
				writer.close();
213
			} catch (IOException e) {
214
			}
215
		}
165
		}
216
	}
166
	}
217
}
167
}
(-)a/org.eclipse.jdt.text.tests/src/org/eclipse/jdt/text/tests/performance/ResourceTestHelper.java (-1 / +3 lines)
Lines 217-223 Link Here
217
217
218
	public static IProject createProjectFromZip(Plugin installationPlugin, String projectZip, String projectName) throws IOException, ZipException, CoreException {
218
	public static IProject createProjectFromZip(Plugin installationPlugin, String projectZip, String projectName) throws IOException, ZipException, CoreException {
219
		String workspacePath= ResourcesPlugin.getWorkspace().getRoot().getLocation().toString() + "/";
219
		String workspacePath= ResourcesPlugin.getWorkspace().getRoot().getLocation().toString() + "/";
220
		FileTool.unzip(new ZipFile(FileTool.getFileInPlugin(installationPlugin, new Path(projectZip))), new File(workspacePath));
220
		try (ZipFile zipFile =new ZipFile(FileTool.getFileInPlugin(installationPlugin, new Path(projectZip)))) { 
221
			FileTool.unzip(zipFile, new File(workspacePath));
222
		}
221
		return createExistingProject(projectName);
223
		return createExistingProject(projectName);
222
	}
224
	}
223
225
(-)a/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/RefactoringTest.java (-5 / +1 lines)
Lines 472-486 Link Here
472
	}
472
	}
473
473
474
	public static String getContents(InputStream in) throws IOException {
474
	public static String getContents(InputStream in) throws IOException {
475
		BufferedReader br= new BufferedReader(new InputStreamReader(in));
476
477
		StringBuffer sb= new StringBuffer(300);
475
		StringBuffer sb= new StringBuffer(300);
478
		try {
476
		try (BufferedReader br= new BufferedReader(new InputStreamReader(in))) {
479
			int read= 0;
477
			int read= 0;
480
			while ((read= br.read()) != -1)
478
			while ((read= br.read()) != -1)
481
				sb.append((char) read);
479
				sb.append((char) read);
482
		} finally {
483
			br.close();
484
		}
480
		}
485
		return sb.toString();
481
		return sb.toString();
486
	}
482
	}
(-)a/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/RenamePackageTests.java (-8 / +2 lines)
Lines 680-693 Link Here
680
680
681
		helper2(new String[]{"my.pack", "my"}, new String[][]{{}, {}}, "my");
681
		helper2(new String[]{"my.pack", "my"}, new String[][]{{}, {}}, "my");
682
682
683
		InputStreamReader reader= new InputStreamReader(textfile.getContents(true));
684
		StringBuffer newContent= new StringBuffer();
683
		StringBuffer newContent= new StringBuffer();
685
		try {
684
		try (InputStreamReader reader= new InputStreamReader(textfile.getContents(true))) {
686
			int ch;
685
			int ch;
687
			while((ch= reader.read()) != -1)
686
			while((ch= reader.read()) != -1)
688
				newContent.append((char)ch);
687
				newContent.append((char)ch);
689
		} finally {
690
			reader.close();
691
		}
688
		}
692
		String definedContent= getFileContents(getTestPath() + getName() + TEST_OUTPUT_INFIX + "my/" + textFileName);
689
		String definedContent= getFileContents(getTestPath() + getName() + TEST_OUTPUT_INFIX + "my/" + textFileName);
693
		assertEqualLines("invalid updating", definedContent, newContent.toString());
690
		assertEqualLines("invalid updating", definedContent, newContent.toString());
Lines 1148-1161 Link Here
1148
1145
1149
		helper2(new String[]{"r.p1", "r"}, new String[][]{{"A"}, {"A"}}, "q");
1146
		helper2(new String[]{"r.p1", "r"}, new String[][]{{"A"}, {"A"}}, "q");
1150
1147
1151
		InputStreamReader reader= new InputStreamReader(textfile.getContents(true));
1152
		StringBuffer newContent= new StringBuffer();
1148
		StringBuffer newContent= new StringBuffer();
1153
		try {
1149
		try (InputStreamReader reader= new InputStreamReader(textfile.getContents(true))) {
1154
			int ch;
1150
			int ch;
1155
			while((ch= reader.read()) != -1)
1151
			while((ch= reader.read()) != -1)
1156
				newContent.append((char)ch);
1152
				newContent.append((char)ch);
1157
		} finally {
1158
			reader.close();
1159
		}
1153
		}
1160
		String definedContent= getFileContents(getTestPath() + getName() + TEST_OUTPUT_INFIX + textFileName);
1154
		String definedContent= getFileContents(getTestPath() + getName() + TEST_OUTPUT_INFIX + textFileName);
1161
		assertEqualLines("invalid updating", definedContent, newContent.toString());
1155
		assertEqualLines("invalid updating", definedContent, newContent.toString());
(-)a/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/RenameTypeTests.java (-8 / +2 lines)
Lines 1222-1235 Link Here
1222
1222
1223
		ICompilationUnit newcu= getPackageP().getCompilationUnit(newName + ".java");
1223
		ICompilationUnit newcu= getPackageP().getCompilationUnit(newName + ".java");
1224
		assertEqualLines("invalid renaming", getFileContents(getOutputTestFileName(newName)), newcu.getSource());
1224
		assertEqualLines("invalid renaming", getFileContents(getOutputTestFileName(newName)), newcu.getSource());
1225
		InputStreamReader reader= new InputStreamReader(file.getContents(true));
1226
		StringBuffer newContent= new StringBuffer();
1225
		StringBuffer newContent= new StringBuffer();
1227
		try {
1226
		try (InputStreamReader reader= new InputStreamReader(file.getContents(true))) {
1228
			int ch;
1227
			int ch;
1229
			while((ch= reader.read()) != -1)
1228
			while((ch= reader.read()) != -1)
1230
				newContent.append((char)ch);
1229
				newContent.append((char)ch);
1231
		} finally {
1232
			reader.close();
1233
		}
1230
		}
1234
		String definedContent= getFileContents(getTestPath() + getName() + TEST_OUTPUT_INFIX + textFileName);
1231
		String definedContent= getFileContents(getTestPath() + getName() + TEST_OUTPUT_INFIX + textFileName);
1235
		assertEqualLines("invalid updating", definedContent, newContent.toString());
1232
		assertEqualLines("invalid updating", definedContent, newContent.toString());
Lines 1330-1343 Link Here
1330
1327
1331
		helper3("SomeClass", "SomeDifferentClass", true, true, true, "test.html");
1328
		helper3("SomeClass", "SomeDifferentClass", true, true, true, "test.html");
1332
1329
1333
		InputStreamReader reader= new InputStreamReader(file.getContents(true));
1334
		StringBuffer newContent= new StringBuffer();
1330
		StringBuffer newContent= new StringBuffer();
1335
		try {
1331
		try (InputStreamReader reader= new InputStreamReader(file.getContents(true))) {
1336
			int ch;
1332
			int ch;
1337
			while((ch= reader.read()) != -1)
1333
			while((ch= reader.read()) != -1)
1338
				newContent.append((char)ch);
1334
				newContent.append((char)ch);
1339
		} finally {
1340
			reader.close();
1341
		}
1335
		}
1342
		String definedContent= getFileContents(getTestPath() + "testSimilarElements05/out/test.html");
1336
		String definedContent= getFileContents(getTestPath() + "testSimilarElements05/out/test.html");
1343
		assertEqualLines("invalid updating test.html", newContent.toString(), definedContent);
1337
		assertEqualLines("invalid updating test.html", newContent.toString(), definedContent);
(-)a/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/infra/AbstractCUTestCase.java (-5 / +1 lines)
Lines 29-43 Link Here
29
	}
29
	}
30
30
31
	protected String getFileContents(InputStream in) throws IOException {
31
	protected String getFileContents(InputStream in) throws IOException {
32
		BufferedReader br= new BufferedReader(new InputStreamReader(in));
33
34
		StringBuffer sb= new StringBuffer();
32
		StringBuffer sb= new StringBuffer();
35
		try {
33
		try (BufferedReader br= new BufferedReader(new InputStreamReader(in))) {
36
			int read= 0;
34
			int read= 0;
37
			while ((read= br.read()) != -1)
35
			while ((read= br.read()) != -1)
38
				sb.append((char) read);
36
				sb.append((char) read);
39
		} finally {
40
			br.close();
41
		}
37
		}
42
		return sb.toString();
38
		return sb.toString();
43
	}
39
	}
(-)a/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/nls/NLSHintTest.java (-3 / +3 lines)
Lines 292-300 Link Here
292
    private IFile createResource(IPackageFragment pack, String resourceName, String content) throws Exception {
292
    private IFile createResource(IPackageFragment pack, String resourceName, String content) throws Exception {
293
	    IPath path = pack.getPath().append(resourceName);
293
	    IPath path = pack.getPath().append(resourceName);
294
	    IFile file = ResourcesPlugin.getWorkspace().getRoot().getFile(path);
294
	    IFile file = ResourcesPlugin.getWorkspace().getRoot().getFile(path);
295
	    InputStream is = new ByteArrayInputStream(content.getBytes());
295
	    try (InputStream is = new ByteArrayInputStream(content.getBytes())) {
296
	    file.create(is, true, new NullProgressMonitor());
296
	    	file.create(is, true, new NullProgressMonitor());
297
	    is.close();
297
	    }
298
        return file;
298
        return file;
299
	}
299
	}
300
300
(-)a/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/nls/NlsRefactoringCreateChangeTest.java (-11 / +8 lines)
Lines 770-793 Link Here
770
	}
770
	}
771
771
772
	private void checkContentOfFile(String message, IFile file, String content) throws Exception {
772
	private void checkContentOfFile(String message, IFile file, String content) throws Exception {
773
		InputStream in= file.getContents();
773
		try (InputStream in= file.getContents()) {
774
		try {
775
			String realContent= copyToString(in);
774
			String realContent= copyToString(in);
776
			RefactoringTest.assertEqualLines(message, content, realContent);
775
			RefactoringTest.assertEqualLines(message, content, realContent);
777
		} finally {
778
			in.close();
779
		}
776
		}
780
	}
777
	}
781
778
782
	private String copyToString(InputStream in) throws Exception {
779
	private String copyToString(InputStream in) throws Exception {
783
		ByteArrayOutputStream out= new ByteArrayOutputStream();
780
		try (ByteArrayOutputStream out= new ByteArrayOutputStream()) {
784
		int read= in.read();
781
			int read= in.read();
785
		while (read != -1) {
782
			while (read != -1) {
786
			out.write(read);
783
				out.write(read);
787
			read= in.read();
784
				read= in.read();
785
			}
786
			return out.toString();
788
		}
787
		}
789
		out.close();
790
		return out.toString();
791
	}
788
	}
792
789
793
	private NLSRefactoring createDefaultNls(ICompilationUnit cu) {
790
	private NLSRefactoring createDefaultNls(ICompilationUnit cu) {
(-)a/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/nls/NlsRefactoringTestHelper.java (-3 / +3 lines)
Lines 84-92 Link Here
84
84
85
    private IFile createFile(IPath path, String content) throws Exception {
85
    private IFile createFile(IPath path, String content) throws Exception {
86
        IFile file = ResourcesPlugin.getWorkspace().getRoot().getFile(path);
86
        IFile file = ResourcesPlugin.getWorkspace().getRoot().getFile(path);
87
        InputStream iS = getInputStream(content);
87
        try (InputStream iS = getInputStream(content)) {
88
        file.create(iS, true, fNpm);
88
        	file.create(iS, true, fNpm);
89
        iS.close();
89
        }
90
        return file;
90
        return file;
91
    }
91
    }
92
92
(-)a/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/template/java/TemplateSet.java (-26 / +2 lines)
Lines 85-106 Link Here
85
	 * @see #addFromStream(InputStream, boolean)
85
	 * @see #addFromStream(InputStream, boolean)
86
	 */
86
	 */
87
	public void addFromFile(File file, boolean allowDuplicates) throws CoreException {
87
	public void addFromFile(File file, boolean allowDuplicates) throws CoreException {
88
		InputStream stream= null;
88
		try (InputStream stream= new FileInputStream(file)) {
89
90
		try {
91
			stream= new FileInputStream(file);
92
			addFromStream(stream, allowDuplicates);
89
			addFromStream(stream, allowDuplicates);
93
94
		} catch (IOException e) {
90
		} catch (IOException e) {
95
			throwReadException(e);
91
			throwReadException(e);
96
97
		} finally {
98
			try {
99
				if (stream != null)
100
					stream.close();
101
			} catch (IOException e) {
102
				// just exit
103
			}
104
		}
92
		}
105
	}
93
	}
106
94
Lines 205-226 Link Here
205
	 * @see #saveToStream(OutputStream)
193
	 * @see #saveToStream(OutputStream)
206
	 */
194
	 */
207
	public void saveToFile(File file) throws CoreException {
195
	public void saveToFile(File file) throws CoreException {
208
		OutputStream stream= null;
196
		try (OutputStream stream= new FileOutputStream(file)) {
209
210
		try {
211
			stream= new FileOutputStream(file);
212
			saveToStream(stream);
197
			saveToStream(stream);
213
214
		} catch (IOException e) {
198
		} catch (IOException e) {
215
			throwWriteException(e);
199
			throwWriteException(e);
216
217
		} finally {
218
			try {
219
				if (stream != null)
220
					stream.close();
221
			} catch (IOException e) {
222
				// just exit
223
			}
224
		}
200
		}
225
	}
201
	}
226
202
(-)a/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/util/History.java (-21 / +2 lines)
Lines 165-185 Link Here
165
		IPath stateLocation= JavaPlugin.getDefault().getStateLocation().append(fFileName);
165
		IPath stateLocation= JavaPlugin.getDefault().getStateLocation().append(fFileName);
166
		File file= stateLocation.toFile();
166
		File file= stateLocation.toFile();
167
		if (file.exists()) {
167
		if (file.exists()) {
168
			InputStreamReader reader= null;
168
			try (InputStreamReader reader = new InputStreamReader(new FileInputStream(file), "utf-8")) { //$NON-NLS-1$
169
	        try {
170
				reader = new InputStreamReader(new FileInputStream(file), "utf-8");//$NON-NLS-1$
171
				load(new InputSource(reader));
169
				load(new InputSource(reader));
172
			} catch (IOException e) {
170
			} catch (IOException e) {
173
				JavaPlugin.log(e);
171
				JavaPlugin.log(e);
174
			} catch (CoreException e) {
172
			} catch (CoreException e) {
175
				JavaPlugin.log(e);
173
				JavaPlugin.log(e);
176
			} finally {
177
				try {
178
					if (reader != null)
179
						reader.close();
180
				} catch (IOException e) {
181
					JavaPlugin.log(e);
182
				}
183
			}
174
			}
184
		}
175
		}
185
	}
176
	}
Lines 187-195 Link Here
187
	public synchronized void save() {
178
	public synchronized void save() {
188
		IPath stateLocation= JavaPlugin.getDefault().getStateLocation().append(fFileName);
179
		IPath stateLocation= JavaPlugin.getDefault().getStateLocation().append(fFileName);
189
		File file= stateLocation.toFile();
180
		File file= stateLocation.toFile();
190
		OutputStream out= null;
181
		try (OutputStream out= new FileOutputStream(file)) {
191
		try {
192
			out= new FileOutputStream(file);
193
			save(out);
182
			save(out);
194
		} catch (IOException e) {
183
		} catch (IOException e) {
195
			JavaPlugin.log(e);
184
			JavaPlugin.log(e);
Lines 199-212 Link Here
199
			// The XML library can be misconficgured (e.g. via
188
			// The XML library can be misconficgured (e.g. via
200
			// -Djava.endorsed.dirs=C:\notExisting\xerces-2_7_1)
189
			// -Djava.endorsed.dirs=C:\notExisting\xerces-2_7_1)
201
			JavaPlugin.log(e);
190
			JavaPlugin.log(e);
202
		} finally {
203
			try {
204
				if (out != null) {
205
					out.close();
206
				}
207
			} catch (IOException e) {
208
				JavaPlugin.log(e);
209
			}
210
		}
191
		}
211
	}
192
	}
212
193
(-)a/org.eclipse.jdt.ui/core refactoring/org/eclipse/jdt/internal/corext/refactoring/changes/DeletePackageFragmentRootChange.java (-16 / +19 lines)
Lines 156-179 Link Here
156
156
157
	private static int getFileLength(IFile file) throws CoreException {
157
	private static int getFileLength(IFile file) throws CoreException {
158
		// Cannot use file buffers here, since they are not yet in sync at this point.
158
		// Cannot use file buffers here, since they are not yet in sync at this point.
159
		InputStream contents= file.getContents();
159
		try (InputStream contents= file.getContents()) {
160
		InputStreamReader reader;
160
			@SuppressWarnings("resource")
161
		try {
161
			InputStreamReader reader = null;
162
			reader= new InputStreamReader(contents, file.getCharset());
162
			try {
163
		} catch (UnsupportedEncodingException e) {
163
				reader= new InputStreamReader(contents, file.getCharset());
164
			JavaPlugin.log(e);
164
			} catch (UnsupportedEncodingException e) {
165
			reader= new InputStreamReader(contents);
165
				JavaPlugin.log(e);
166
		}
166
				reader= new InputStreamReader(contents);
167
		try {
167
			}
168
			return (int) reader.skip(Integer.MAX_VALUE);
168
			try {
169
				return (int) reader.skip(Integer.MAX_VALUE);
170
			} finally {
171
				try {
172
					reader.close();
173
				} catch (IOException e) {
174
					// ignore
175
				}
176
			}
169
		} catch (IOException e) {
177
		} catch (IOException e) {
170
			throw new CoreException(new Status(IStatus.ERROR, Corext.getPluginId(), e.getMessage(), e));
178
			throw new CoreException(new Status(IStatus.ERROR, Corext.getPluginId(), e.getMessage(), e));
171
		} finally {
179
		} 
172
			try {
173
				reader.close();
174
			} catch (IOException e) {
175
			}
176
		}
177
	}
180
	}
178
181
179
	private boolean confirmDeleteIfReferenced() throws JavaModelException {
182
	private boolean confirmDeleteIfReferenced() throws JavaModelException {
(-)a/org.eclipse.jdt.ui/core refactoring/org/eclipse/jdt/internal/corext/refactoring/nls/changes/CreateFileChange.java (-10 / +3 lines)
Lines 146-152 Link Here
146
	@Override
146
	@Override
147
	public Change perform(IProgressMonitor pm) throws CoreException, OperationCanceledException {
147
	public Change perform(IProgressMonitor pm) throws CoreException, OperationCanceledException {
148
148
149
		InputStream is= null;
150
		try {
149
		try {
151
			pm.beginTask(NLSChangesMessages.createFile_creating_resource, 3);
150
			pm.beginTask(NLSChangesMessages.createFile_creating_resource, 3);
152
151
Lines 160-167 Link Here
160
				pm.worked(1);
159
				pm.worked(1);
161
				return composite.perform(new SubProgressMonitor(pm, 1));
160
				return composite.perform(new SubProgressMonitor(pm, 1));
162
			} else { */
161
			} else { */
163
			try {
162
			try (InputStream is= new ByteArrayInputStream(fSource.getBytes(fEncoding))) {
164
				is= new ByteArrayInputStream(fSource.getBytes(fEncoding));
165
				file.create(is, false, new SubProgressMonitor(pm, 1));
163
				file.create(is, false, new SubProgressMonitor(pm, 1));
166
				if (fStampToRestore != IResource.NULL_STAMP) {
164
				if (fStampToRestore != IResource.NULL_STAMP) {
167
					file.revertModificationStamp(fStampToRestore);
165
					file.revertModificationStamp(fStampToRestore);
Lines 174-189 Link Here
174
				return new DeleteResourceChange(file.getFullPath(), true);
172
				return new DeleteResourceChange(file.getFullPath(), true);
175
			} catch (UnsupportedEncodingException e) {
173
			} catch (UnsupportedEncodingException e) {
176
				throw new JavaModelException(e, IJavaModelStatusConstants.IO_EXCEPTION);
174
				throw new JavaModelException(e, IJavaModelStatusConstants.IO_EXCEPTION);
177
			}
178
		} finally {
179
			try {
180
				if (is != null)
181
					is.close();
182
			} catch (IOException ioe) {
175
			} catch (IOException ioe) {
183
				throw new JavaModelException(ioe, IJavaModelStatusConstants.IO_EXCEPTION);
176
				throw new JavaModelException(ioe, IJavaModelStatusConstants.IO_EXCEPTION);
184
			} finally {
185
				pm.done();
186
			}
177
			}
178
		} finally {
179
			pm.done();
187
		}
180
		}
188
	}
181
	}
189
182
(-)a/org.eclipse.jdt.ui/core refactoring/org/eclipse/jdt/internal/corext/refactoring/nls/changes/CreateTextFileChange.java (-9 / +3 lines)
Lines 41-60 Link Here
41
		IFile file= getOldFile(new NullProgressMonitor());
41
		IFile file= getOldFile(new NullProgressMonitor());
42
		if (! file.exists())
42
		if (! file.exists())
43
			return ""; //$NON-NLS-1$
43
			return ""; //$NON-NLS-1$
44
		InputStream stream= null;
44
		try (InputStream stream= file.getContents()) {
45
		try{
46
			stream= file.getContents();
47
			String encoding= file.getCharset();
45
			String encoding= file.getCharset();
48
			String c= NLSUtil.readString(stream, encoding);
46
			String c= NLSUtil.readString(stream, encoding);
49
			return (c == null) ? "": c; //$NON-NLS-1$
47
			return (c == null) ? "": c; //$NON-NLS-1$
50
		} catch (CoreException e){
48
		} catch (CoreException e){
51
			throw new JavaModelException(e, IJavaModelStatusConstants.CORE_EXCEPTION);
49
			throw new JavaModelException(e, IJavaModelStatusConstants.CORE_EXCEPTION);
52
		} finally {
50
		} catch (IOException e) {
53
			try {
51
			throw new JavaModelException(e, IJavaModelStatusConstants.IO_EXCEPTION);
54
				if (stream != null)
55
					stream.close();
56
			} catch (IOException x) {
57
			}
58
		}
52
		}
59
	}
53
	}
60
54
(-)a/org.eclipse.jdt.ui/core refactoring/org/eclipse/jdt/internal/corext/refactoring/reorg/JavaElementTransfer.java (-7 / +2 lines)
Lines 70-78 Link Here
70
		 *  (String) handle identifier
70
		 *  (String) handle identifier
71
		 */
71
		 */
72
72
73
		try {
73
		try (ByteArrayOutputStream out= new ByteArrayOutputStream();
74
			ByteArrayOutputStream out= new ByteArrayOutputStream();
74
				DataOutputStream dataOut= new DataOutputStream(out)) {
75
			DataOutputStream dataOut= new DataOutputStream(out);
76
75
77
			//write the number of elements
76
			//write the number of elements
78
			dataOut.writeInt(javaElements.length);
77
			dataOut.writeInt(javaElements.length);
Lines 81-90 Link Here
81
			for (int i= 0; i < javaElements.length; i++) {
80
			for (int i= 0; i < javaElements.length; i++) {
82
				writeJavaElement(dataOut, javaElements[i]);
81
				writeJavaElement(dataOut, javaElements[i]);
83
			}
82
			}
84
85
			//cleanup
86
			dataOut.close();
87
			out.close();
88
			byte[] bytes= out.toByteArray();
83
			byte[] bytes= out.toByteArray();
89
			super.javaToNative(bytes, transferData);
84
			super.javaToNative(bytes, transferData);
90
		} catch (IOException e) {
85
		} catch (IOException e) {
(-)a/org.eclipse.jdt.ui/jar in jar loader/org/eclipse/jdt/internal/jarinjarloader/JarRsrcLoader.java (-18 / +18 lines)
Lines 53-81 Link Here
53
		}
53
		}
54
		ClassLoader jceClassLoader = new URLClassLoader(rsrcUrls, null);
54
		ClassLoader jceClassLoader = new URLClassLoader(rsrcUrls, null);
55
		Thread.currentThread().setContextClassLoader(jceClassLoader);
55
		Thread.currentThread().setContextClassLoader(jceClassLoader);
56
		Class c = Class.forName(mi.rsrcMainClass, true, jceClassLoader);
56
		Class<?> c = Class.forName(mi.rsrcMainClass, true, jceClassLoader);
57
		Method main = c.getMethod(JIJConstants.MAIN_METHOD_NAME, new Class[]{args.getClass()}); 
57
		Method main = c.getMethod(JIJConstants.MAIN_METHOD_NAME, new Class[]{args.getClass()}); 
58
		main.invoke((Object)null, new Object[]{args});
58
		main.invoke((Object)null, new Object[]{args});
59
	}
59
	}
60
60
61
	private static ManifestInfo getManifestInfo() throws IOException {
61
	private static ManifestInfo getManifestInfo() throws IOException {
62
		Enumeration resEnum;
62
		Enumeration<URL> resEnum = Thread.currentThread().getContextClassLoader().getResources(JarFile.MANIFEST_NAME); 
63
		resEnum = Thread.currentThread().getContextClassLoader().getResources(JarFile.MANIFEST_NAME); 
64
		while (resEnum.hasMoreElements()) {
63
		while (resEnum.hasMoreElements()) {
65
			try {
64
			try {
66
				URL url = (URL)resEnum.nextElement();
65
				URL url = resEnum.nextElement();
67
				InputStream is = url.openStream();
66
				try (InputStream is = url.openStream()) {
68
				if (is != null) {
67
					if (is != null) {
69
					ManifestInfo result = new ManifestInfo();
68
						ManifestInfo result = new ManifestInfo();
70
					Manifest manifest = new Manifest(is);
69
						Manifest manifest = new Manifest(is);
71
					Attributes mainAttribs = manifest.getMainAttributes();
70
						Attributes mainAttribs = manifest.getMainAttributes();
72
					result.rsrcMainClass = mainAttribs.getValue(JIJConstants.REDIRECTED_MAIN_CLASS_MANIFEST_NAME); 
71
						result.rsrcMainClass = mainAttribs.getValue(JIJConstants.REDIRECTED_MAIN_CLASS_MANIFEST_NAME); 
73
					String rsrcCP = mainAttribs.getValue(JIJConstants.REDIRECTED_CLASS_PATH_MANIFEST_NAME); 
72
						String rsrcCP = mainAttribs.getValue(JIJConstants.REDIRECTED_CLASS_PATH_MANIFEST_NAME); 
74
					if (rsrcCP == null)
73
						if (rsrcCP == null)
75
						rsrcCP = JIJConstants.DEFAULT_REDIRECTED_CLASSPATH; 
74
							rsrcCP = JIJConstants.DEFAULT_REDIRECTED_CLASSPATH; 
76
					result.rsrcClassPath = splitSpaces(rsrcCP);
75
						result.rsrcClassPath = splitSpaces(rsrcCP);
77
					if ((result.rsrcMainClass != null) && !result.rsrcMainClass.trim().equals(""))    //$NON-NLS-1$
76
						if ((result.rsrcMainClass != null) && !result.rsrcMainClass.trim().equals(""))    //$NON-NLS-1$
78
							return result;
77
								return result;
78
					}
79
				}
79
				}
80
			}
80
			}
81
			catch (Exception e) {
81
			catch (Exception e) {
Lines 96-102 Link Here
96
	private static String[] splitSpaces(String line) {
96
	private static String[] splitSpaces(String line) {
97
		if (line == null) 
97
		if (line == null) 
98
			return null;
98
			return null;
99
		List result = new ArrayList();
99
		List<String> result = new ArrayList<>();
100
		int firstPos = 0;
100
		int firstPos = 0;
101
		while (firstPos < line.length()) {
101
		while (firstPos < line.length()) {
102
			int lastPos = line.indexOf(' ', firstPos);
102
			int lastPos = line.indexOf(' ', firstPos);
Lines 107-113 Link Here
107
			}
107
			}
108
			firstPos = lastPos+1; 
108
			firstPos = lastPos+1; 
109
		}
109
		}
110
		return (String[]) result.toArray(new String[result.size()]);
110
		return result.toArray(new String[result.size()]);
111
	}
111
	}
112
112
113
}
113
}
(-)a/org.eclipse.jdt.ui/jar in jar loader/org/eclipse/jdt/internal/jarinjarloader/RsrcURLConnection.java (+2 lines)
Lines 36-44 Link Here
36
		this.classLoader= classLoader;
36
		this.classLoader= classLoader;
37
	}
37
	}
38
38
39
	@Override
39
	public void connect() throws IOException {
40
	public void connect() throws IOException {
40
	}
41
	}
41
42
43
	@Override
42
	public InputStream getInputStream() throws IOException {
44
	public InputStream getInputStream() throws IOException {
43
		String file= URLDecoder.decode(url.getFile(), JIJConstants.UTF8_ENCODING);
45
		String file= URLDecoder.decode(url.getFile(), JIJConstants.UTF8_ENCODING);
44
		InputStream result= classLoader.getResourceAsStream(file);
46
		InputStream result= classLoader.getResourceAsStream(file);
(-)a/org.eclipse.jdt.ui/jar in jar loader/org/eclipse/jdt/internal/jarinjarloader/RsrcURLStreamHandler.java (-1 / +3 lines)
Lines 34-44 Link Here
34
    	this.classLoader = classLoader;
34
    	this.classLoader = classLoader;
35
	}
35
	}
36
36
37
	@Override
37
	protected java.net.URLConnection openConnection(URL u) throws IOException {
38
	protected java.net.URLConnection openConnection(URL u) throws IOException {
38
    	return new RsrcURLConnection(u, classLoader);
39
    	return new RsrcURLConnection(u, classLoader);
39
    }
40
    }
40
41
41
    protected void parseURL(URL url, String spec, int start, int limit) {
42
    @Override
43
	protected void parseURL(URL url, String spec, int start, int limit) {
42
    	String file;
44
    	String file;
43
    	if (spec.startsWith(JIJConstants.INTERNAL_URL_PROTOCOL_WITH_COLON))  
45
    	if (spec.startsWith(JIJConstants.INTERNAL_URL_PROTOCOL_WITH_COLON))  
44
    		file = spec.substring(5);
46
    		file = spec.substring(5);
(-)a/org.eclipse.jdt.ui/jar in jar loader/org/eclipse/jdt/internal/jarinjarloader/RsrcURLStreamHandlerFactory.java (+1 lines)
Lines 31-36 Link Here
31
		this.classLoader = cl;
31
		this.classLoader = cl;
32
	}
32
	}
33
33
34
	@Override
34
	public URLStreamHandler createURLStreamHandler(String protocol) {
35
	public URLStreamHandler createURLStreamHandler(String protocol) {
35
		if (JIJConstants.INTERNAL_URL_PROTOCOL.equals(protocol)) 
36
		if (JIJConstants.INTERNAL_URL_PROTOCOL.equals(protocol)) 
36
			return new RsrcURLStreamHandler(classLoader);
37
			return new RsrcURLStreamHandler(classLoader);
(-)a/org.eclipse.jdt.ui/ui refactoring/org/eclipse/jdt/internal/ui/refactoring/nls/ExternalizeWizardPage.java (-6 / +7 lines)
Added Link Here
11
 *******************************************************************************/
11
 *******************************************************************************/
12
package org.eclipse.jdt.internal.ui.refactoring.nls;
12
package org.eclipse.jdt.internal.ui.refactoring.nls;
13
13
14
import java.io.IOException;
14
import java.io.InputStream;
15
import java.io.InputStream;
15
import java.util.ArrayList;
16
import java.util.ArrayList;
16
import java.util.Collections;
17
import java.util.Collections;
Added Link Here
698
699
699
	private Properties getProperties(IFile propertyFile) {
700
	private Properties getProperties(IFile propertyFile) {
700
		Properties props= new Properties();
701
		Properties props= new Properties();
701
		try {
702
		if (propertyFile.exists()) {
702
			if (propertyFile.exists()) {
703
			try (InputStream is= propertyFile.getContents()) {
703
				InputStream is= propertyFile.getContents();
704
				props.load(is);
704
				props.load(is);
705
				is.close();
705
			} catch (IOException e) {
706
				// sorry no property
707
			} catch (CoreException e) {
708
				// sorry no property
706
			}
709
			}
707
		} catch (Exception e) {
708
			// sorry no property
709
		}
710
		}
710
		return props;
711
		return props;
711
	}
712
	}
(-)a/org.eclipse.jdt.ui/ui refactoring/org/eclipse/jdt/internal/ui/refactoring/nls/search/LineReader.java (-1 / +2 lines)
Lines 17-23 Link Here
17
import java.io.Reader;
17
import java.io.Reader;
18
18
19
19
20
class LineReader extends Object {
20
class LineReader extends Object implements AutoCloseable {
21
	protected static final int LF= '\n';
21
	protected static final int LF= '\n';
22
	protected static final int CR= '\r';
22
	protected static final int CR= '\r';
23
23
Lines 62-67 Link Here
62
		return -1;
62
		return -1;
63
	}
63
	}
64
64
65
	@Override
65
	public void close() throws IOException {
66
	public void close() throws IOException {
66
		fReader.close();
67
		fReader.close();
67
	}
68
	}
(-)a/org.eclipse.jdt.ui/ui refactoring/org/eclipse/jdt/internal/ui/refactoring/nls/search/NLSSearchResultRequestor.java (-58 / +36 lines)
Lines 325-413 Link Here
325
	 */
325
	 */
326
	private int findPropertyNameStartPosition(String propertyName) {
326
	private int findPropertyNameStartPosition(String propertyName) {
327
		// Fix for http://dev.eclipse.org/bugs/show_bug.cgi?id=19319
327
		// Fix for http://dev.eclipse.org/bugs/show_bug.cgi?id=19319
328
		InputStream stream= null;
329
		LineReader lineReader= null;
330
		String encoding;
328
		String encoding;
331
		try {
329
		try {
332
			encoding= fPropertiesFile.getCharset();
330
			encoding= fPropertiesFile.getCharset();
333
		} catch (CoreException e1) {
331
		} catch (CoreException e1) {
334
			encoding= "ISO-8859-1";  //$NON-NLS-1$
332
			encoding= "ISO-8859-1";  //$NON-NLS-1$
335
		}
333
		}
336
		try {
334
		try (InputStream stream= createInputStream(fPropertiesFile)) {
337
			stream= createInputStream(fPropertiesFile);
335
			try (LineReader lineReader= new LineReader(stream, encoding)) {
338
			lineReader= new LineReader(stream, encoding);
336
				int start= 0;
337
				try {
338
					StringBuffer buf= new StringBuffer(80);
339
					int eols= lineReader.readLine(buf);
340
					int keyLength= propertyName.length();
341
					while (eols > 0) {
342
						String line= buf.toString();
343
						int i= line.indexOf(propertyName);
344
						int charPos= i + keyLength;
345
						char terminatorChar= 0;
346
						boolean hasNoValue= (charPos >= line.length());
347
						if (i > -1 && !hasNoValue)
348
							terminatorChar= line.charAt(charPos);
349
						if (line.trim().startsWith(propertyName) &&
350
								(hasNoValue || Character.isWhitespace(terminatorChar) || terminatorChar == '=')) {
351
							start += line.indexOf(propertyName);
352
							eols= -17; // found key
353
						} else {
354
							start += line.length() + eols;
355
							buf.setLength(0);
356
							eols= lineReader.readLine(buf);
357
						}
358
					}
359
					if (eols != -17)
360
						start= -1; //key not found in file. See bug 63794. This can happen if the key contains escaped characters.
361
				} catch (IOException ex) {
362
					JavaPlugin.log(ex);
363
					return -1;
364
				}
365
				return start;
366
			}
339
		} catch (CoreException cex) {
367
		} catch (CoreException cex) {
340
			// failed to get input stream
368
			// failed to get input stream
341
			JavaPlugin.log(cex);
369
			JavaPlugin.log(cex);
342
			return -1;
370
			return -1;
343
		} catch (IOException e) {
371
		} catch (IOException e) {
344
			if (stream != null) {
372
			JavaPlugin.log(e);
345
				try {
346
					stream.close();
347
				} catch (IOException ce) {
348
					JavaPlugin.log(ce);
349
				}
350
			}
351
			return -1;
373
			return -1;
352
		}
374
		}
353
		int start= 0;
354
		try {
355
			StringBuffer buf= new StringBuffer(80);
356
			int eols= lineReader.readLine(buf);
357
			int keyLength= propertyName.length();
358
			while (eols > 0) {
359
				String line= buf.toString();
360
				int i= line.indexOf(propertyName);
361
				int charPos= i + keyLength;
362
				char terminatorChar= 0;
363
				boolean hasNoValue= (charPos >= line.length());
364
				if (i > -1 && !hasNoValue)
365
					terminatorChar= line.charAt(charPos);
366
				if (line.trim().startsWith(propertyName) &&
367
						(hasNoValue || Character.isWhitespace(terminatorChar) || terminatorChar == '=')) {
368
					start += line.indexOf(propertyName);
369
					eols= -17; // found key
370
				} else {
371
					start += line.length() + eols;
372
					buf.setLength(0);
373
					eols= lineReader.readLine(buf);
374
				}
375
			}
376
			if (eols != -17)
377
				start= -1; //key not found in file. See bug 63794. This can happen if the key contains escaped characters.
378
		} catch (IOException ex) {
379
			JavaPlugin.log(ex);
380
			return -1;
381
		} finally {
382
			try {
383
				lineReader.close();
384
			} catch (IOException ex) {
385
				JavaPlugin.log(ex);
386
			}
387
		}
388
		return start;
389
	}
375
	}
390
376
391
	private void loadProperties() {
377
	private void loadProperties() {
392
		Set<Object> duplicateKeys= new HashSet<>();
378
		Set<Object> duplicateKeys= new HashSet<>();
393
		fProperties= new Properties(duplicateKeys);
379
		fProperties= new Properties(duplicateKeys);
394
		InputStream stream;
380
		try (InputStream stream= new BufferedInputStream(createInputStream(fPropertiesFile))) {
395
		try {
381
			fProperties.load(stream);
396
			stream= new BufferedInputStream(createInputStream(fPropertiesFile));
397
		} catch (CoreException ex) {
382
		} catch (CoreException ex) {
398
			fProperties= new Properties();
383
			fProperties= new Properties();
399
			return;
384
			return;
400
		}
401
		try {
402
			fProperties.load(stream);
403
		} catch (IOException ex) {
385
		} catch (IOException ex) {
404
			fProperties= new Properties();
386
			fProperties= new Properties();
405
			return;
387
			return;
406
		} finally {
388
		} finally {
407
			try {
408
				stream.close();
409
			} catch (IOException ex) {
410
			}
411
			reportDuplicateKeys(duplicateKeys);
389
			reportDuplicateKeys(duplicateKeys);
412
		}
390
		}
413
	}
391
	}
(-)a/org.eclipse.jdt.ui/ui refactoring/org/eclipse/jdt/internal/ui/refactoring/reorg/TypedSourceTransfer.java (-10 / +3 lines)
Lines 72-90 Link Here
72
		 *  (String) source of the element
72
		 *  (String) source of the element
73
		 */
73
		 */
74
74
75
		try {
75
		try (ByteArrayOutputStream out = new ByteArrayOutputStream();
76
			ByteArrayOutputStream out = new ByteArrayOutputStream();
76
			DataOutputStream dataOut = new DataOutputStream(out)) {
77
			DataOutputStream dataOut = new DataOutputStream(out);
78
77
79
			dataOut.writeInt(sources.length);
78
			dataOut.writeInt(sources.length);
80
79
81
			for (int i = 0; i < sources.length; i++) {
80
			for (int i = 0; i < sources.length; i++) {
82
				writeJavaElement(dataOut, sources[i]);
81
				writeJavaElement(dataOut, sources[i]);
83
			}
82
			}
84
85
			dataOut.close();
86
			out.close();
87
88
			super.javaToNative(out.toByteArray(), transferData);
83
			super.javaToNative(out.toByteArray(), transferData);
89
		} catch (IOException e) {
84
		} catch (IOException e) {
90
			//it's best to send nothing if there were problems
85
			//it's best to send nothing if there were problems
Lines 97-111 Link Here
97
		byte[] bytes = (byte[]) super.nativeToJava(transferData);
92
		byte[] bytes = (byte[]) super.nativeToJava(transferData);
98
		if (bytes == null)
93
		if (bytes == null)
99
			return null;
94
			return null;
100
		DataInputStream in = new DataInputStream(new ByteArrayInputStream(bytes));
95
		try (DataInputStream in = new DataInputStream(new ByteArrayInputStream(bytes))) {
101
		try {
102
			int count = in.readInt();
96
			int count = in.readInt();
103
			TypedSource[] results = new TypedSource[count];
97
			TypedSource[] results = new TypedSource[count];
104
			for (int i = 0; i < count; i++) {
98
			for (int i = 0; i < count; i++) {
105
				results[i] = readJavaElement(in);
99
				results[i] = readJavaElement(in);
106
				Assert.isNotNull(results[i]);
100
				Assert.isNotNull(results[i]);
107
			}
101
			}
108
			in.close();
109
			return results;
102
			return results;
110
		} catch (IOException e) {
103
		} catch (IOException e) {
111
			return null;
104
			return null;
(-)a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/fix/CleanUpRefactoringWizard.java (-8 / +8 lines)
Lines 38-43 Link Here
38
38
39
import org.eclipse.core.runtime.CoreException;
39
import org.eclipse.core.runtime.CoreException;
40
import org.eclipse.core.runtime.IStatus;
40
import org.eclipse.core.runtime.IStatus;
41
import org.eclipse.core.runtime.Status;
41
import org.eclipse.core.runtime.preferences.IEclipsePreferences;
42
import org.eclipse.core.runtime.preferences.IEclipsePreferences;
42
import org.eclipse.core.runtime.preferences.InstanceScope;
43
import org.eclipse.core.runtime.preferences.InstanceScope;
43
44
Lines 475-482 Link Here
475
        }
476
        }
476
477
477
		public String encodeSettings(Map<String, String> settings) throws CoreException {
478
		public String encodeSettings(Map<String, String> settings) throws CoreException {
478
			ByteArrayOutputStream stream= new ByteArrayOutputStream(2000);
479
			try (ByteArrayOutputStream stream= new ByteArrayOutputStream(2000)) {
479
			try {
480
				CleanUpProfileVersioner versioner= new CleanUpProfileVersioner();
480
				CleanUpProfileVersioner versioner= new CleanUpProfileVersioner();
481
				CustomProfile profile= new ProfileManager.CustomProfile("custom", settings, versioner.getCurrentVersion(), versioner.getProfileKind()); //$NON-NLS-1$
481
				CustomProfile profile= new ProfileManager.CustomProfile("custom", settings, versioner.getCurrentVersion(), versioner.getProfileKind()); //$NON-NLS-1$
482
				ArrayList<Profile> profiles= new ArrayList<>();
482
				ArrayList<Profile> profiles= new ArrayList<>();
Lines 487-494 Link Here
487
				} catch (UnsupportedEncodingException e) {
487
				} catch (UnsupportedEncodingException e) {
488
					return stream.toString();
488
					return stream.toString();
489
				}
489
				}
490
			} finally {
490
			} catch (IOException e) {
491
				try { stream.close(); } catch (IOException e) { /* ignore */ }
491
				throw new CoreException(new Status(IStatus.ERROR, JavaPlugin.getPluginId(), e.getMessage(), e));
492
			}
492
			}
493
		}
493
		}
494
494
Lines 499-506 Link Here
499
			} catch (UnsupportedEncodingException e) {
499
			} catch (UnsupportedEncodingException e) {
500
				bytes= settings.getBytes();
500
				bytes= settings.getBytes();
501
			}
501
			}
502
			InputStream is= new ByteArrayInputStream(bytes);
502
			try (InputStream is= new ByteArrayInputStream(bytes)) {
503
			try {
504
				List<Profile> res= ProfileStore.readProfilesFromStream(new InputSource(is));
503
				List<Profile> res= ProfileStore.readProfilesFromStream(new InputSource(is));
505
				if (res == null || res.size() == 0)
504
				if (res == null || res.size() == 0)
506
					return JavaPlugin.getDefault().getCleanUpRegistry().getDefaultOptions(CleanUpConstants.DEFAULT_CLEAN_UP_OPTIONS).getMap();
505
					return JavaPlugin.getDefault().getCleanUpRegistry().getDefaultOptions(CleanUpConstants.DEFAULT_CLEAN_UP_OPTIONS).getMap();
Lines 508-515 Link Here
508
				CustomProfile profile= (CustomProfile)res.get(0);
507
				CustomProfile profile= (CustomProfile)res.get(0);
509
				new CleanUpProfileVersioner().update(profile);
508
				new CleanUpProfileVersioner().update(profile);
510
				return profile.getSettings();
509
				return profile.getSettings();
511
			} finally {
510
			} catch (IOException e) {
512
				try { is.close(); } catch (IOException e) { /* ignore */ }
511
				// ignore
512
				return null;
513
			}
513
			}
514
		}
514
		}
515
515
(-)a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/infoviews/SourceView.java (-9 / +2 lines)
Lines 467-491 Link Here
467
	 * @return the source without leading comments
467
	 * @return the source without leading comments
468
	 */
468
	 */
469
	private String removeLeadingComments(String source) {
469
	private String removeLeadingComments(String source) {
470
		JavaCodeReader reader= new JavaCodeReader();
471
		IDocument document= new Document(source);
470
		IDocument document= new Document(source);
472
		int i;
471
		int i;
473
		try {
472
		try (JavaCodeReader reader= new JavaCodeReader()) {
474
			reader.configureForwardReader(document, 0, document.getLength(), true, false);
473
			reader.configureForwardReader(document, 0, document.getLength(), true, false);
475
			int c= reader.read();
474
			int c= reader.read();
476
			while (c != -1 && (c == '\r' || c == '\n' || c == '\t')) {
475
			while (c != -1 && (c == '\r' || c == '\n' || c == '\t')) {
477
				c= reader.read();
476
				c= reader.read();
478
			}
477
			}
479
			i= reader.getOffset();
478
			i= reader.getOffset();
480
			reader.close();
481
		} catch (IOException ex) {
479
		} catch (IOException ex) {
482
			i= 0;
480
			i= 0;
483
		} finally {
481
			JavaPlugin.log(ex);
484
			try {
485
				reader.close();
486
			} catch (IOException ex) {
487
				JavaPlugin.log(ex);
488
			}
489
		}
482
		}
490
483
491
		try {
484
		try {
(-)a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/jarimport/JarImportWizard.java (-18 / +3 lines)
Lines 103-134 Link Here
103
						if (uri != null) {
103
						if (uri != null) {
104
							final File file= new File(uri);
104
							final File file= new File(uri);
105
							if (file.exists()) {
105
							if (file.exists()) {
106
								ZipFile zip= null;
106
								try (ZipFile zip= new ZipFile(file, ZipFile.OPEN_READ)) {
107
								try {
108
									zip= new ZipFile(file, ZipFile.OPEN_READ);
109
									ZipEntry entry= zip.getEntry(JarPackagerUtil.getRefactoringsEntry());
107
									ZipEntry entry= zip.getEntry(JarPackagerUtil.getRefactoringsEntry());
110
									if (entry != null) {
108
									if (entry != null) {
111
										InputStream stream= null;
109
										try (InputStream stream= zip.getInputStream(entry)) {
112
										try {
113
											stream= zip.getInputStream(entry);
114
											final RefactoringHistory existing= RefactoringCore.getHistoryService().readRefactoringHistory(stream, JavaRefactoringDescriptor.JAR_MIGRATION | JavaRefactoringDescriptor.JAR_REFACTORING);
110
											final RefactoringHistory existing= RefactoringCore.getHistoryService().readRefactoringHistory(stream, JavaRefactoringDescriptor.JAR_MIGRATION | JavaRefactoringDescriptor.JAR_REFACTORING);
115
											if (existing != null)
111
											if (existing != null)
116
												fHistoryDelta= incoming.removeAll(existing).getDescriptors();
112
												fHistoryDelta= incoming.removeAll(existing).getDescriptors();
117
										} finally {
118
											if (stream != null) {
119
												try {
120
													stream.close();
121
												} catch (IOException exception) {
122
													// Do nothing
123
												}
124
											}
125
										}
113
										}
126
									}
114
									}
127
								} catch (IOException exception) {
115
								} catch (IOException exception) {
128
									try {
116
									// ignore
129
										zip.close();
130
									} catch(IOException e){
131
									}
132
								}
117
								}
133
							}
118
							}
134
						}
119
						}
(-)a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/jarimport/JarImportWizardPage.java (-37 / +7 lines)
Lines 368-382 Link Here
368
					setPageComplete(false);
368
					setPageComplete(false);
369
					return;
369
					return;
370
				}
370
				}
371
				ZipFile zip= null;
371
				try (ZipFile zip= new ZipFile(file, ZipFile.OPEN_READ)) {
372
				try {
373
					try {
374
						zip= new ZipFile(file, ZipFile.OPEN_READ);
375
					} catch (IOException exception) {
376
						setErrorMessage(JarImportMessages.JarImportWizardPage_invalid_location);
377
						setPageComplete(false);
378
						return;
379
					}
380
					final JarImportData data= fWizard.getImportData();
372
					final JarImportData data= fWizard.getImportData();
381
					data.setRefactoringFileLocation(URIUtil.toURI(path));
373
					data.setRefactoringFileLocation(URIUtil.toURI(path));
382
					ZipEntry entry= zip.getEntry(JarPackagerUtil.getRefactoringsEntry());
374
					ZipEntry entry= zip.getEntry(JarPackagerUtil.getRefactoringsEntry());
Lines 391-399 Link Here
391
						setPageComplete(true);
383
						setPageComplete(true);
392
						return;
384
						return;
393
					}
385
					}
394
					InputStream stream= null;
386
					try (InputStream stream= zip.getInputStream(entry)) {
395
					try {
396
						stream= zip.getInputStream(entry);
397
						data.setRefactoringHistory(RefactoringCore.getHistoryService().readRefactoringHistory(stream, JavaRefactoringDescriptor.JAR_MIGRATION | JavaRefactoringDescriptor.JAR_REFACTORING));
387
						data.setRefactoringHistory(RefactoringCore.getHistoryService().readRefactoringHistory(stream, JavaRefactoringDescriptor.JAR_MIGRATION | JavaRefactoringDescriptor.JAR_REFACTORING));
398
					} catch (IOException exception) {
388
					} catch (IOException exception) {
399
						setErrorMessage(JarImportMessages.JarImportWizardPage_no_refactorings);
389
						setErrorMessage(JarImportMessages.JarImportWizardPage_no_refactorings);
Lines 404-425 Link Here
404
						setErrorMessage(JarImportMessages.JarImportWizardPage_no_refactorings);
394
						setErrorMessage(JarImportMessages.JarImportWizardPage_no_refactorings);
405
						setPageComplete(false);
395
						setPageComplete(false);
406
						return;
396
						return;
407
					} finally {
408
						if (stream != null) {
409
							try {
410
								stream.close();
411
							} catch (IOException exception) {
412
								// Do nothing
413
							}
414
						}
415
					}
397
					}
416
				} finally {
398
				} catch (IOException exception) {
417
					if (zip != null) {
399
					setErrorMessage(JarImportMessages.JarImportWizardPage_invalid_location);
418
						try {
400
					setPageComplete(false);
419
							zip.close();
401
					return;
420
						} catch (IOException e) {
421
						}
422
					}
423
				}
402
				}
424
			}
403
			}
425
		}
404
		}
Lines 462-483 Link Here
462
				if (uri != null) {
441
				if (uri != null) {
463
					final File file= new File(uri);
442
					final File file= new File(uri);
464
					if (file.exists()) {
443
					if (file.exists()) {
465
						ZipFile zip= null;
444
						try (ZipFile zip= new ZipFile(file, ZipFile.OPEN_READ)) {
466
						try {
467
							zip= new ZipFile(file, ZipFile.OPEN_READ);
468
							ZipEntry entry= zip.getEntry(JarPackagerUtil.getRefactoringsEntry());
445
							ZipEntry entry= zip.getEntry(JarPackagerUtil.getRefactoringsEntry());
469
							if (entry != null) {
446
							if (entry != null) {
470
								fWizard.getImportData().setExistingTimeStamp(entry.getTime());
447
								fWizard.getImportData().setExistingTimeStamp(entry.getTime());
471
							}
448
							}
472
						} catch (IOException exception) {
449
						} catch (IOException exception) {
473
							// Just leave it
450
							// Just leave it
474
						} finally {
475
							if (zip != null) {
476
								try {
477
									zip.close();
478
								} catch (IOException e) {
479
								}
480
							}
481
						}
451
						}
482
					}
452
					}
483
				}
453
				}
(-)a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/jarpackager/JarFileExportOperation.java (-34 / +11 lines)
Lines 213-233 Link Here
213
					if (element instanceof IPackageFragmentRoot) {
213
					if (element instanceof IPackageFragmentRoot) {
214
						IPackageFragmentRoot root= (IPackageFragmentRoot) element;
214
						IPackageFragmentRoot root= (IPackageFragmentRoot) element;
215
						if (root.isArchive()) {
215
						if (root.isArchive()) {
216
							ZipFile file= null;
216
							try (ZipFile file = JarPackagerUtil.getArchiveFile(root.getPath())) {
217
							try {
218
								file= JarPackagerUtil.getArchiveFile(root.getPath());
219
								if (file != null)
217
								if (file != null)
220
									count+= file.size();
218
									count+= file.size();
221
							} catch (CoreException e) {
219
							} catch (CoreException e) {
222
								JavaPlugin.log(e);
220
								JavaPlugin.log(e);
223
							} finally {
221
							} catch (IOException e) {
224
								try {
222
								addWarning(Messages.format(JarPackagerMessages.JarFileExportOperation_CloseZipFileError_message, new Object[] { JavaElementLabels.getElementLabel(root, JavaElementLabels.ALL_DEFAULT), e.getLocalizedMessage() }), e);
225
									if (file != null) {
226
										file.close();
227
									}
228
								} catch (IOException e) {
229
									addWarning(Messages.format(JarPackagerMessages.JarFileExportOperation_CloseZipFileError_message, new Object[] { JavaElementLabels.getElementLabel(root, JavaElementLabels.ALL_DEFAULT), e.getLocalizedMessage() }), e);
230
								}
231
							}
223
							}
232
						} else if (root.isExternal()) {
224
						} else if (root.isExternal()) {
233
							try {
225
							try {
Lines 394-413 Link Here
394
	private void exportJavaElement(IProgressMonitor progressMonitor, IJavaElement je) throws InterruptedException {
386
	private void exportJavaElement(IProgressMonitor progressMonitor, IJavaElement je) throws InterruptedException {
395
		if (je.getElementType() == IJavaElement.PACKAGE_FRAGMENT_ROOT && ((IPackageFragmentRoot) je).isArchive()) {
387
		if (je.getElementType() == IJavaElement.PACKAGE_FRAGMENT_ROOT && ((IPackageFragmentRoot) je).isArchive()) {
396
			IPackageFragmentRoot root= (IPackageFragmentRoot) je;
388
			IPackageFragmentRoot root= (IPackageFragmentRoot) je;
397
			ZipFile jarFile= null;
389
			try (ZipFile jarFile= JarPackagerUtil.getArchiveFile(root.getPath())) {
398
			try {
399
				jarFile= JarPackagerUtil.getArchiveFile(root.getPath());
400
				fJarBuilder.writeArchive(jarFile, progressMonitor);
390
				fJarBuilder.writeArchive(jarFile, progressMonitor);
401
			} catch (CoreException e) {
391
			} catch (CoreException e) {
402
				addWarning(Messages.format(JarPackagerMessages.JarFileExportOperation_OpenZipFileError_message, new Object[] { JavaElementLabels.getElementLabel(root, JavaElementLabels.ALL_DEFAULT), e.getLocalizedMessage() }), e);
392
				addWarning(Messages.format(JarPackagerMessages.JarFileExportOperation_OpenZipFileError_message, new Object[] { JavaElementLabels.getElementLabel(root, JavaElementLabels.ALL_DEFAULT), e.getLocalizedMessage() }), e);
403
			} finally {
393
			} catch (IOException e) {
404
				try {
394
				addWarning(Messages.format(JarPackagerMessages.JarFileExportOperation_CloseZipFileError_message, new Object[] { JavaElementLabels.getElementLabel(root, JavaElementLabels.ALL_DEFAULT), e.getLocalizedMessage() }), e);
405
					if (jarFile != null) {
406
						jarFile.close();
407
					}
408
				} catch (IOException e) {
409
					addWarning(Messages.format(JarPackagerMessages.JarFileExportOperation_CloseZipFileError_message, new Object[] { JavaElementLabels.getElementLabel(root, JavaElementLabels.ALL_DEFAULT), e.getLocalizedMessage() }), e);
410
				}
411
			}
395
			}
412
			return;
396
			return;
413
		} else if (je.getElementType() == IJavaElement.PACKAGE_FRAGMENT_ROOT && ((IPackageFragmentRoot) je).isExternal()) {
397
		} else if (je.getElementType() == IJavaElement.PACKAGE_FRAGMENT_ROOT && ((IPackageFragmentRoot) je).isExternal()) {
Lines 843-861 Link Here
843
				IFile classFile= (IFile)members[i];
827
				IFile classFile= (IFile)members[i];
844
				URI location= classFile.getLocationURI();
828
				URI location= classFile.getLocationURI();
845
				if (location != null) {
829
				if (location != null) {
846
					InputStream contents= null;
830
					try (InputStream contents= EFS.getStore(location).openInputStream(EFS.NONE, monitor)) {
847
					try {
848
						contents= EFS.getStore(location).openInputStream(EFS.NONE, monitor);
849
						cfReader= ToolFactory.createDefaultClassFileReader(contents, IClassFileReader.CLASSFILE_ATTRIBUTES);
831
						cfReader= ToolFactory.createDefaultClassFileReader(contents, IClassFileReader.CLASSFILE_ATTRIBUTES);
850
					} finally {
832
					} catch (IOException e) {
851
						try {
833
						throw new CoreException(new Status(IStatus.ERROR, JavaPlugin.getPluginId(), IStatus.ERROR,
852
							if (contents != null)
834
							Messages.format(JarPackagerMessages.JarFileExportOperation_errorCannotCloseConnection, BasicElementLabels.getURLPart(Resources.getLocationString(classFile))),
853
								contents.close();
835
							e));
854
						} catch (IOException e) {
855
							throw new CoreException(new Status(IStatus.ERROR, JavaPlugin.getPluginId(), IStatus.ERROR,
856
								Messages.format(JarPackagerMessages.JarFileExportOperation_errorCannotCloseConnection, BasicElementLabels.getURLPart(Resources.getLocationString(classFile))),
857
								e));
858
						}
859
					}
836
					}
860
					if (cfReader != null) {
837
					if (cfReader != null) {
861
						ISourceAttribute sourceAttribute= cfReader.getSourceFileAttribute();
838
						ISourceAttribute sourceAttribute= cfReader.getSourceFileAttribute();
(-)a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/jarpackager/ManifestProvider.java (-5 / +1 lines)
Lines 123-134 Link Here
123
	private Manifest createSuppliedManifest(JarPackageData jarPackage) throws CoreException, IOException {
123
	private Manifest createSuppliedManifest(JarPackageData jarPackage) throws CoreException, IOException {
124
		Manifest manifest;
124
		Manifest manifest;
125
		// No need to use buffer here because Manifest(...) does
125
		// No need to use buffer here because Manifest(...) does
126
		InputStream stream= jarPackage.getManifestFile().getContents(false);
126
		try (InputStream stream= jarPackage.getManifestFile().getContents(false)) {
127
		try {
128
			manifest= new Manifest(stream);
127
			manifest= new Manifest(stream);
129
		} finally {
130
			if (stream != null)
131
				stream.close();
132
		}
128
		}
133
		return manifest;
129
		return manifest;
134
	}
130
	}
(-)a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/jarpackagerfat/FatJarManifestProvider.java (-18 / +4 lines)
Lines 69-88 Link Here
69
						while (entries.hasMoreElements()) {
69
						while (entries.hasMoreElements()) {
70
							ZipEntry entry= entries.nextElement();
70
							ZipEntry entry= entries.nextElement();
71
							if (entry.getName().equalsIgnoreCase("META-INF/MANIFEST.MF")) { //$NON-NLS-1$
71
							if (entry.getName().equalsIgnoreCase("META-INF/MANIFEST.MF")) { //$NON-NLS-1$
72
								InputStream inputStream= null;
72
								try (InputStream inputStream= zip.getInputStream(entry)) {
73
								try {
74
									inputStream= zip.getInputStream(entry);
75
									Manifest otherManifest= new Manifest(inputStream);
73
									Manifest otherManifest= new Manifest(inputStream);
76
									otherManifests.add(otherManifest);
74
									otherManifests.add(otherManifest);
77
								} catch (IOException e) {
75
								} catch (IOException e) {
78
									JavaPlugin.log(e);
76
									JavaPlugin.log(e);
79
								} finally {
80
									if (inputStream != null) {
81
										try {
82
											inputStream.close();
83
										} catch(IOException e){
84
										}
85
									}
86
								}
77
								}
87
							}
78
							}
88
						}
79
						}
Lines 91-99 Link Here
91
				result= merge(ownManifest, otherManifests);
82
				result= merge(ownManifest, otherManifests);
92
			} finally {
83
			} finally {
93
				for (Iterator<ZipFile> iter= openZips.iterator(); iter.hasNext(); ) {
84
				for (Iterator<ZipFile> iter= openZips.iterator(); iter.hasNext(); ) {
94
					ZipFile file= iter.next();
85
					try (ZipFile file = iter.next()) {
95
					try {
86
						// nothing to do
96
						file.close();
97
					} catch (IOException e) {
87
					} catch (IOException e) {
98
						JavaPlugin.log(e);
88
						JavaPlugin.log(e);
99
					}
89
					}
Lines 205-216 Link Here
205
	private Manifest createSuppliedManifest(JarPackageData jarPackage) throws CoreException, IOException {
195
	private Manifest createSuppliedManifest(JarPackageData jarPackage) throws CoreException, IOException {
206
		Manifest manifest;
196
		Manifest manifest;
207
		// No need to use buffer here because Manifest(...) does
197
		// No need to use buffer here because Manifest(...) does
208
		InputStream stream= jarPackage.getManifestFile().getContents(false);
198
		try (InputStream stream= jarPackage.getManifestFile().getContents(false)) {
209
		try {
210
			manifest= new Manifest(stream);
199
			manifest= new Manifest(stream);
211
		} finally {
212
			if (stream != null)
213
				stream.close();
214
		}
200
		}
215
		return manifest;
201
		return manifest;
216
	}
202
	}
(-)a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/jarpackagerfat/FatJarRsrcUrlAntExporter.java (-11 / +12 lines)
Lines 57-78 Link Here
57
	@Override
57
	@Override
58
	protected void buildANTScript(IPath antScriptLocation, String projectName, IPath absJarfile, String mainClass, SourceInfo[] sourceInfos) throws FileNotFoundException, IOException {
58
	protected void buildANTScript(IPath antScriptLocation, String projectName, IPath absJarfile, String mainClass, SourceInfo[] sourceInfos) throws FileNotFoundException, IOException {
59
		File antScriptFile= antScriptLocation.toFile();
59
		File antScriptFile= antScriptLocation.toFile();
60
		buildANTScript(new FileOutputStream(antScriptFile), projectName, absJarfile, mainClass, sourceInfos);
60
		try (OutputStream output = new FileOutputStream(antScriptFile)) {
61
			buildANTScript(output, projectName, absJarfile, mainClass, sourceInfos);
62
		}
61
		copyJarInJarLoader(new File(antScriptFile.getParentFile(), FatJarRsrcUrlBuilder.JAR_RSRC_LOADER_ZIP));
63
		copyJarInJarLoader(new File(antScriptFile.getParentFile(), FatJarRsrcUrlBuilder.JAR_RSRC_LOADER_ZIP));
62
	}
64
	}
63
65
64
	private void copyJarInJarLoader(File targetFile) throws IOException {
66
	private void copyJarInJarLoader(File targetFile) throws IOException {
65
		InputStream is= JavaPlugin.getDefault().getBundle().getEntry(FatJarRsrcUrlBuilder.JAR_RSRC_LOADER_ZIP).openStream();
67
		try (InputStream is= JavaPlugin.getDefault().getBundle().getEntry(FatJarRsrcUrlBuilder.JAR_RSRC_LOADER_ZIP).openStream();
66
		OutputStream os= new FileOutputStream(targetFile);
68
				OutputStream os= new FileOutputStream(targetFile)) {
67
		byte[] buf= new byte[1024];
69
			byte[] buf= new byte[1024];
68
		while (true) {
70
			while (true) {
69
			int cnt= is.read(buf);
71
				int cnt= is.read(buf);
70
			if (cnt <= 0)
72
				if (cnt <= 0)
71
				break;
73
					break;
72
			os.write(buf, 0, cnt);
74
				os.write(buf, 0, cnt);
75
			}
73
		}
76
		}
74
		os.close();
75
		is.close();
76
	}
77
	}
77
78
78
	protected void buildANTScript(OutputStream outputStream, String projectName, IPath absJarfile, String mainClass, SourceInfo[] sourceInfos) throws IOException {
79
	protected void buildANTScript(OutputStream outputStream, String projectName, IPath absJarfile, String mainClass, SourceInfo[] sourceInfos) throws IOException {
(-)a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/jarpackagerfat/UnpackFatJarAntExporter.java (-7 / +1 lines)
Lines 47-55 Link Here
47
47
48
	@Override
48
	@Override
49
	protected void buildANTScript(IPath antScriptLocation, String projectName, IPath absJarfile, String mainClass, SourceInfo[] sourceInfos) throws IOException {
49
	protected void buildANTScript(IPath antScriptLocation, String projectName, IPath absJarfile, String mainClass, SourceInfo[] sourceInfos) throws IOException {
50
		OutputStream outputStream= null;
50
		try (OutputStream outputStream= new FileOutputStream(antScriptLocation.toFile())) {
51
		try {
52
			outputStream= new FileOutputStream(antScriptLocation.toFile());
53
			String absJarname= absJarfile.toString();
51
			String absJarname= absJarfile.toString();
54
52
55
			DocumentBuilder docBuilder= null;
53
			DocumentBuilder docBuilder= null;
Lines 124-133 Link Here
124
				transformer.transform(source, result);
122
				transformer.transform(source, result);
125
			} catch (TransformerException e) {
123
			} catch (TransformerException e) {
126
				throw new IOException(FatJarPackagerMessages.FatJarPackageAntScript_error_couldNotTransformToXML);
124
				throw new IOException(FatJarPackagerMessages.FatJarPackageAntScript_error_couldNotTransformToXML);
127
			}
128
		} finally {
129
			if (outputStream != null) {
130
				outputStream.close();
131
			}
125
			}
132
		}
126
		}
133
	}
127
	}
(-)a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/jarpackagerfat/UnpackJarAntExporter.java (-7 / +1 lines)
Lines 51-59 Link Here
51
51
52
	@Override
52
	@Override
53
	protected void buildANTScript(IPath antScriptLocation, String projectName, IPath absJarfile, String mainClass, SourceInfo[] sourceInfos) throws IOException {
53
	protected void buildANTScript(IPath antScriptLocation, String projectName, IPath absJarfile, String mainClass, SourceInfo[] sourceInfos) throws IOException {
54
		OutputStream outputStream= null;
54
		try (OutputStream outputStream= new FileOutputStream(antScriptLocation.toFile())) {
55
		try {
56
			outputStream= new FileOutputStream(antScriptLocation.toFile());
57
			String absJarname= absJarfile.toString();
55
			String absJarname= absJarfile.toString();
58
			String subfolder= absJarfile.removeFileExtension().lastSegment() + "_lib"; //$NON-NLS-1$
56
			String subfolder= absJarfile.removeFileExtension().lastSegment() + "_lib"; //$NON-NLS-1$
59
			String absSubfolder= absJarfile.removeLastSegments(1).append(subfolder).toString();
57
			String absSubfolder= absJarfile.removeLastSegments(1).append(subfolder).toString();
Lines 161-170 Link Here
161
				transformer.transform(source, result);
159
				transformer.transform(source, result);
162
			} catch (TransformerException e) {
160
			} catch (TransformerException e) {
163
				throw new IOException(FatJarPackagerMessages.FatJarPackageAntScript_error_couldNotTransformToXML);
161
				throw new IOException(FatJarPackagerMessages.FatJarPackageAntScript_error_couldNotTransformToXML);
164
			}
165
		} finally {
166
			if (outputStream != null) {
167
				outputStream.close();
168
			}
162
			}
169
		}
163
		}
170
	}
164
	}
(-)a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/jarpackagerfat/UnpackJarBuilder.java (-14 / +2 lines)
Lines 165-175 Link Here
165
	}
165
	}
166
166
167
	private void copyFile(File src, File dest) {
167
	private void copyFile(File src, File dest) {
168
		InputStream in= null;
168
		try (InputStream in= new FileInputStream(src);
169
		OutputStream out= null;
169
				OutputStream out= new FileOutputStream(dest)) {
170
		try {
171
			in= new FileInputStream(src);
172
			out= new FileOutputStream(dest);
173
			byte[] buf= new byte[4096];
170
			byte[] buf= new byte[4096];
174
			int cnt= in.read(buf);
171
			int cnt= in.read(buf);
175
			while (cnt > 0) {
172
			while (cnt > 0) {
Lines 182-196 Link Here
182
			throw new RuntimeException(e);
179
			throw new RuntimeException(e);
183
		} catch (IOException e) {
180
		} catch (IOException e) {
184
			throw new RuntimeException(e);
181
			throw new RuntimeException(e);
185
		} finally {
186
			try {
187
				out.close();
188
			} catch (IOException ignore) {
189
			}
190
			try {
191
				in.close();
192
			} catch (IOException ignore) {
193
			}
194
		}
182
		}
195
	}
183
	}
196
	
184
	
(-)a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/javadocexport/JavadocOptionsManager.java (-10 / +3 lines)
Lines 859-865 Link Here
859
859
860
860
861
	public File writeXML(Element javadocElement) throws CoreException {
861
	public File writeXML(Element javadocElement) throws CoreException {
862
		FileOutputStream objectStreamOutput= null;
863
		//@change
862
		//@change
864
		//for now only writing ant files for single project selection
863
		//for now only writing ant files for single project selection
865
		try {
864
		try {
Lines 872-879 Link Here
872
871
873
			file.getParentFile().mkdirs();
872
			file.getParentFile().mkdirs();
874
873
875
			objectStreamOutput= new FileOutputStream(file);
874
			try (FileOutputStream objectStreamOutput= new FileOutputStream(file)) {
876
			JavadocWriter.writeDocument(javadocElement, encoding, objectStreamOutput);
875
				JavadocWriter.writeDocument(javadocElement, encoding, objectStreamOutput);
876
			}
877
			return file;
877
			return file;
878
		} catch (IOException e) {
878
		} catch (IOException e) {
879
			String message= JavadocExportMessages.JavadocOptionsManager_createXM_error;
879
			String message= JavadocExportMessages.JavadocOptionsManager_createXM_error;
Lines 881-893 Link Here
881
		} catch (TransformerException e) {
881
		} catch (TransformerException e) {
882
			String message= JavadocExportMessages.JavadocOptionsManager_createXM_error;
882
			String message= JavadocExportMessages.JavadocOptionsManager_createXM_error;
883
			throw new CoreException(JavaUIStatus.createError(IStatus.ERROR, message, e));
883
			throw new CoreException(JavaUIStatus.createError(IStatus.ERROR, message, e));
884
		} finally {
885
			if (objectStreamOutput != null) {
886
				try {
887
					objectStreamOutput.close();
888
				} catch (IOException e) {
889
				}
890
			}
891
		}
884
		}
892
	}
885
	}
893
886
(-)a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/javadocexport/JavadocWizard.java (-4 / +1 lines)
Lines 298-305 Link Here
298
			File file= File.createTempFile("javadoc-arguments", ".tmp");  //$NON-NLS-1$//$NON-NLS-2$
298
			File file= File.createTempFile("javadoc-arguments", ".tmp");  //$NON-NLS-1$//$NON-NLS-2$
299
			vmArgs.add('@' + file.getAbsolutePath());
299
			vmArgs.add('@' + file.getAbsolutePath());
300
300
301
			BufferedWriter writer= new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), getEncoding(vmArgs)));
301
			try (BufferedWriter writer= new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), getEncoding(vmArgs)))) {
302
			try {
303
				for (int i= 0; i < progArgs.size(); i++) {
302
				for (int i= 0; i < progArgs.size(); i++) {
304
					String curr= progArgs.get(i);
303
					String curr= progArgs.get(i);
305
					curr= checkForSpaces(curr);
304
					curr= checkForSpaces(curr);
Lines 307-314 Link Here
307
					writer.write(curr);
306
					writer.write(curr);
308
					writer.write(' ');
307
					writer.write(' ');
309
				}
308
				}
310
			} finally {
311
				writer.close();
312
			}
309
			}
313
			String[] args= vmArgs.toArray(new String[vmArgs.size()]);
310
			String[] args= vmArgs.toArray(new String[vmArgs.size()]);
314
			process= Runtime.getRuntime().exec(args);
311
			process= Runtime.getRuntime().exec(args);
(-)a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/javaeditor/ClipboardOperationAction.java (-12 / +3 lines)
Lines 109-121 Link Here
109
		}
109
		}
110
110
111
		public ClipboardData(byte[] bytes) throws IOException {
111
		public ClipboardData(byte[] bytes) throws IOException {
112
			DataInputStream dataIn = new DataInputStream(new ByteArrayInputStream(bytes));
112
			try (DataInputStream dataIn = new DataInputStream(new ByteArrayInputStream(bytes))) {
113
			try {
114
				fOriginHandle= dataIn.readUTF();
113
				fOriginHandle= dataIn.readUTF();
115
				fTypeImports= readArray(dataIn);
114
				fTypeImports= readArray(dataIn);
116
				fStaticImports= readArray(dataIn);
115
				fStaticImports= readArray(dataIn);
117
			} finally {
118
				dataIn.close();
119
			}
116
			}
120
		}
117
		}
121
118
Lines 149-166 Link Here
149
		}
146
		}
150
147
151
		public byte[] serialize() throws IOException {
148
		public byte[] serialize() throws IOException {
152
			ByteArrayOutputStream out = new ByteArrayOutputStream();
149
			try (ByteArrayOutputStream out = new ByteArrayOutputStream(); DataOutputStream dataOut = new DataOutputStream(out)) {
153
			DataOutputStream dataOut = new DataOutputStream(out);
154
			try {
155
				dataOut.writeUTF(fOriginHandle);
150
				dataOut.writeUTF(fOriginHandle);
156
				writeArray(dataOut, fTypeImports);
151
				writeArray(dataOut, fTypeImports);
157
				writeArray(dataOut, fStaticImports);
152
				writeArray(dataOut, fStaticImports);
158
			} finally {
153
				return out.toByteArray();
159
				dataOut.close();
160
				out.close();
161
			}
154
			}
162
163
			return out.toByteArray();
164
		}
155
		}
165
	}
156
	}
166
157
(-)a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/javaeditor/InternalClassFileEditorInput.java (-13 / +6 lines)
Lines 160-183 Link Here
160
	}
160
	}
161
161
162
	private static IPath writeToTempFile(IClassFile classFile) {
162
	private static IPath writeToTempFile(IClassFile classFile) {
163
		FileOutputStream writer= null;
164
		try {
163
		try {
165
			File file= File.createTempFile(classFile.getElementName(), ".class"); //$NON-NLS-1$
164
			File file= File.createTempFile(classFile.getElementName(), ".class"); //$NON-NLS-1$
166
			byte[] bytes= classFile.getBytes();
165
			byte[] bytes= classFile.getBytes();
167
			writer= new FileOutputStream(file);
166
			try (FileOutputStream writer= new FileOutputStream(file)) {
168
			writer.write(bytes);
167
				writer.write(bytes);
169
			return new Path(file.toString());
168
				return new Path(file.toString());
170
		} catch (IOException e) {
169
			}
171
			JavaPlugin.log(e);
172
		} catch (CoreException e) {
170
		} catch (CoreException e) {
173
			JavaPlugin.log(e.getStatus());
171
			JavaPlugin.log(e.getStatus());
174
		} finally {
172
		} catch (IOException e) {
175
			if (writer != null)
173
			JavaPlugin.log(e);
176
				try {
177
					writer.close();
178
				} catch (IOException e) {
179
					JavaPlugin.log(e);
180
				}
181
		}
174
		}
182
		throw new IllegalArgumentException("Could not create temporary file."); //$NON-NLS-1$
175
		throw new IllegalArgumentException("Could not create temporary file."); //$NON-NLS-1$
183
	}
176
	}
(-)a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/preferences/CodeTemplateBlock.java (-34 / +12 lines)
Lines 15-21 Link Here
15
import java.io.BufferedOutputStream;
15
import java.io.BufferedOutputStream;
16
import java.io.File;
16
import java.io.File;
17
import java.io.FileInputStream;
17
import java.io.FileInputStream;
18
import java.io.FileNotFoundException;
19
import java.io.FileOutputStream;
18
import java.io.FileOutputStream;
20
import java.io.IOException;
19
import java.io.IOException;
21
import java.io.InputStream;
20
import java.io.InputStream;
Lines 480-512 Link Here
480
		if (path == null)
479
		if (path == null)
481
			return;
480
			return;
482
481
483
		try {
482
		TemplateReaderWriter reader= new TemplateReaderWriter();
484
			TemplateReaderWriter reader= new TemplateReaderWriter();
483
		File file= new File(path);
485
			File file= new File(path);
484
		if (file.exists()) {
486
			if (file.exists()) {
485
			try (InputStream input= new BufferedInputStream(new FileInputStream(file))) {
487
				InputStream input= new BufferedInputStream(new FileInputStream(file));
486
				TemplatePersistenceData[] datas= reader.read(input, null);
488
				try {
487
				for (int i= 0; i < datas.length; i++) {
489
					TemplatePersistenceData[] datas= reader.read(input, null);
488
					updateTemplate(datas[i]);
490
					for (int i= 0; i < datas.length; i++) {
491
						updateTemplate(datas[i]);
492
					}
493
				} finally {
494
					try {
495
						input.close();
496
					} catch (IOException x) {
497
					}
498
				}
489
				}
490
			} catch (IOException e) {
491
				openReadErrorDialog(e);
499
			}
492
			}
500
501
			fCodeTemplateTree.refresh();
502
			updateSourceViewerInput(fCodeTemplateTree.getSelectedElements());
503
504
		} catch (FileNotFoundException e) {
505
			openReadErrorDialog(e);
506
		} catch (IOException e) {
507
			openReadErrorDialog(e);
508
		}
493
		}
509
494
495
		fCodeTemplateTree.refresh();
496
		updateSourceViewerInput(fCodeTemplateTree.getSelectedElements());
510
	}
497
	}
511
498
512
	private void updateTemplate(TemplatePersistenceData data) {
499
	private void updateTemplate(TemplatePersistenceData data) {
Lines 567-586 Link Here
567
		}
554
		}
568
555
569
		if (!file.exists() || confirmOverwrite(file)) {
556
		if (!file.exists() || confirmOverwrite(file)) {
570
			OutputStream output= null;
557
			try (OutputStream output= new BufferedOutputStream(new FileOutputStream(file))) {
571
			try {
572
				output= new BufferedOutputStream(new FileOutputStream(file));
573
				TemplateReaderWriter writer= new TemplateReaderWriter();
558
				TemplateReaderWriter writer= new TemplateReaderWriter();
574
				writer.save(templates, output);
559
				writer.save(templates, output);
575
				output.close();
560
				output.close();
576
			} catch (IOException e) {
561
			} catch (IOException e) {
577
				if (output != null) {
578
					try {
579
						output.close();
580
					} catch (IOException e2) {
581
						// ignore
582
					}
583
				}
584
				openWriteErrorDialog();
562
				openWriteErrorDialog();
585
			}
563
			}
586
		}
564
		}
(-)a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/preferences/ImportOrganizeConfigurationBlock.java (-14 / +2 lines)
Lines 352-360 Link Here
352
			dialogSettings.put(DIALOGSETTING_LASTLOADPATH, dialog.getFilterPath());
352
			dialogSettings.put(DIALOGSETTING_LASTLOADPATH, dialog.getFilterPath());
353
353
354
			Properties properties= new Properties();
354
			Properties properties= new Properties();
355
			FileInputStream fis= null;
355
			try (FileInputStream fis= new FileInputStream(fileName)) {
356
			try {
357
				fis= new FileInputStream(fileName);
358
				properties.load(fis);
356
				properties.load(fis);
359
				List<ImportOrderEntry> res= loadFromProperties(properties);
357
				List<ImportOrderEntry> res= loadFromProperties(properties);
360
				if (res != null) {
358
				if (res != null) {
Lines 362-371 Link Here
362
				}
360
				}
363
			} catch (IOException e) {
361
			} catch (IOException e) {
364
				JavaPlugin.log(e);
362
				JavaPlugin.log(e);
365
			} finally {
366
				if (fis != null) {
367
					try { fis.close(); } catch (IOException e) {}
368
				}
369
			}
363
			}
370
			String title= PreferencesMessages.ImportOrganizeConfigurationBlock_loadDialog_error_title;
364
			String title= PreferencesMessages.ImportOrganizeConfigurationBlock_loadDialog_error_title;
371
			String message= PreferencesMessages.ImportOrganizeConfigurationBlock_loadDialog_error_message;
365
			String message= PreferencesMessages.ImportOrganizeConfigurationBlock_loadDialog_error_message;
Lines 394-412 Link Here
394
				ImportOrderEntry entry= elements.get(i);
388
				ImportOrderEntry entry= elements.get(i);
395
				properties.setProperty(String.valueOf(i), entry.serialize());
389
				properties.setProperty(String.valueOf(i), entry.serialize());
396
			}
390
			}
397
			FileOutputStream fos= null;
391
			try (FileOutputStream fos= new FileOutputStream(fileName)) {
398
			try {
399
				fos= new FileOutputStream(fileName);
400
				properties.store(fos, "Organize Import Order"); //$NON-NLS-1$
392
				properties.store(fos, "Organize Import Order"); //$NON-NLS-1$
401
			} catch (IOException e) {
393
			} catch (IOException e) {
402
				JavaPlugin.log(e);
394
				JavaPlugin.log(e);
403
				String title= PreferencesMessages.ImportOrganizeConfigurationBlock_saveDialog_error_title;
395
				String title= PreferencesMessages.ImportOrganizeConfigurationBlock_saveDialog_error_title;
404
				String message= PreferencesMessages.ImportOrganizeConfigurationBlock_saveDialog_error_message;
396
				String message= PreferencesMessages.ImportOrganizeConfigurationBlock_saveDialog_error_message;
405
				MessageDialog.openError(getShell(), title, message);
397
				MessageDialog.openError(getShell(), title, message);
406
			} finally {
407
				if (fos != null) {
408
					try { fos.close(); } catch (IOException e) {}
409
				}
410
			}
398
			}
411
		}
399
		}
412
	}
400
	}
(-)a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/preferences/JavaBasePreferencePage.java (-1 / +1 lines)
Lines 66-72 Link Here
66
	private ArrayList<Button> fCheckBoxes;
66
	private ArrayList<Button> fCheckBoxes;
67
	private ArrayList<Button> fRadioButtons;
67
	private ArrayList<Button> fRadioButtons;
68
	private ArrayList<Text> fTextControls;
68
	private ArrayList<Text> fTextControls;
69
	private static final String PREFERENCE_STORE_KEY = "preferenceStore";
69
	private static final String PREFERENCE_STORE_KEY = "preferenceStore"; //$NON-NLS-1$
70
70
71
	private IPreferenceStore fJavaCorePreferences;
71
	private IPreferenceStore fJavaCorePreferences;
72
72
(-)a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/preferences/JavadocConfigurationBlock.java (-6 / +2 lines)
Lines 418-433 Link Here
418
				connection.connect();
418
				connection.connect();
419
				res= ((HttpURLConnection) connection).getResponseCode();
419
				res= ((HttpURLConnection) connection).getResponseCode();
420
			}
420
			}
421
			InputStream is= null;
421
			try (InputStream is= connection.getInputStream()) {
422
			try {
423
				is= connection.getInputStream();
424
				byte[] buffer= new byte[256];
422
				byte[] buffer= new byte[256];
425
				while (is.read(buffer) != -1) {
423
				while (is.read(buffer) != -1) {
426
					// just read
424
					// just read
427
				}
425
				}
428
			} finally {
429
				if (is != null)
430
					is.close();
431
			}
426
			}
432
		} catch (IllegalArgumentException e) {
427
		} catch (IllegalArgumentException e) {
433
			return false; // workaround for bug 91072
428
			return false; // workaround for bug 91072
Lines 531-536 Link Here
531
	}
526
	}
532
527
533
	private String internalChooseArchivePath() {
528
	private String internalChooseArchivePath() {
529
		@SuppressWarnings("resource")
534
		ZipFile zipFile= null;
530
		ZipFile zipFile= null;
535
		try {
531
		try {
536
			if (fWorkspaceRadio.isSelected()) {
532
			if (fWorkspaceRadio.isSelected()) {
(-)a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/preferences/UserLibraryPreferencePage.java (-11 / +2 lines)
Lines 559-566 Link Here
559
		}
559
		}
560
560
561
		protected static void saveLibraries(List<CPUserLibraryElement> libraries, File file, String encoding, IProgressMonitor monitor) throws IOException {
561
		protected static void saveLibraries(List<CPUserLibraryElement> libraries, File file, String encoding, IProgressMonitor monitor) throws IOException {
562
			OutputStream stream= new FileOutputStream(file);
562
			try (OutputStream stream= new FileOutputStream(file)) {
563
			try {
564
				DocumentBuilder docBuilder= null;
563
				DocumentBuilder docBuilder= null;
565
				DocumentBuilderFactory factory= DocumentBuilderFactory.newInstance();
564
				DocumentBuilderFactory factory= DocumentBuilderFactory.newInstance();
566
				factory.setValidating(false);
565
				factory.setValidating(false);
Lines 635-645 Link Here
635
			} catch (TransformerException e) {
634
			} catch (TransformerException e) {
636
				throw new IOException(e.getMessage());
635
				throw new IOException(e.getMessage());
637
			} finally {
636
			} finally {
638
				try {
639
					stream.close();
640
				} catch (IOException e) {
641
					// ignore
642
				}
643
				if (monitor != null) {
637
				if (monitor != null) {
644
					monitor.done();
638
					monitor.done();
645
				}
639
				}
Lines 647-655 Link Here
647
		}
641
		}
648
642
649
		private static List<CPUserLibraryElement> loadLibraries(File file) throws IOException {
643
		private static List<CPUserLibraryElement> loadLibraries(File file) throws IOException {
650
			InputStream stream= new FileInputStream(file);
651
			Element cpElement;
644
			Element cpElement;
652
			try {
645
			try (InputStream stream= new FileInputStream(file)) {
653
				DocumentBuilder parser = DocumentBuilderFactory.newInstance().newDocumentBuilder();
646
				DocumentBuilder parser = DocumentBuilderFactory.newInstance().newDocumentBuilder();
654
				parser.setErrorHandler(new DefaultHandler());
647
				parser.setErrorHandler(new DefaultHandler());
655
				cpElement = parser.parse(new InputSource(stream)).getDocumentElement();
648
				cpElement = parser.parse(new InputSource(stream)).getDocumentElement();
Lines 657-664 Link Here
657
				throw new IOException(PreferencesMessages.UserLibraryPreferencePage_LoadSaveDialog_load_badformat);
650
				throw new IOException(PreferencesMessages.UserLibraryPreferencePage_LoadSaveDialog_load_badformat);
658
			} catch (ParserConfigurationException e) {
651
			} catch (ParserConfigurationException e) {
659
				throw new IOException(PreferencesMessages.UserLibraryPreferencePage_LoadSaveDialog_load_badformat);
652
				throw new IOException(PreferencesMessages.UserLibraryPreferencePage_LoadSaveDialog_load_badformat);
660
			} finally {
661
				stream.close();
662
			}
653
			}
663
654
664
			if (!cpElement.getNodeName().equalsIgnoreCase(TAG_ROOT)) {
655
			if (!cpElement.getNodeName().equalsIgnoreCase(TAG_ROOT)) {
(-)a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/preferences/formatter/FormatterProfileStore.java (-4 / +1 lines)
Lines 74-81 Link Here
74
74
75
		try {
75
		try {
76
			// note that it's wrong to use a file reader when XML declares UTF-8: Kept for compatibility
76
			// note that it's wrong to use a file reader when XML declares UTF-8: Kept for compatibility
77
			final FileReader reader= new FileReader(file);
77
			try (final FileReader reader= new FileReader(file)) {
78
			try {
79
				List<Profile> res= readProfilesFromStream(new InputSource(reader));
78
				List<Profile> res= readProfilesFromStream(new InputSource(reader));
80
				if (res != null) {
79
				if (res != null) {
81
					for (int i= 0; i < res.size(); i++) {
80
					for (int i= 0; i < res.size(); i++) {
Lines 85-92 Link Here
85
				}
84
				}
86
				file.delete(); // remove after successful write
85
				file.delete(); // remove after successful write
87
				return res;
86
				return res;
88
			} finally {
89
				reader.close();
90
			}
87
			}
91
		} catch (CoreException e) {
88
		} catch (CoreException e) {
92
			JavaPlugin.log(e); // log but ignore
89
			JavaPlugin.log(e); // log but ignore
(-)a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/preferences/formatter/ProfileStore.java (-23 / +10 lines)
Lines 165-172 Link Here
165
	}
165
	}
166
166
167
	public void writeProfiles(Collection<Profile> profiles, IScopeContext instanceScope) throws CoreException {
167
	public void writeProfiles(Collection<Profile> profiles, IScopeContext instanceScope) throws CoreException {
168
		ByteArrayOutputStream stream= new ByteArrayOutputStream(2000);
168
		try (ByteArrayOutputStream stream= new ByteArrayOutputStream(2000)) {
169
		try {
170
			writeProfilesToStream(profiles, stream, ENCODING, fProfileVersioner);
169
			writeProfilesToStream(profiles, stream, ENCODING, fProfileVersioner);
171
			String val;
170
			String val;
172
			try {
171
			try {
Lines 177-184 Link Here
177
			IEclipsePreferences uiPreferences = instanceScope.getNode(JavaUI.ID_PLUGIN);
176
			IEclipsePreferences uiPreferences = instanceScope.getNode(JavaUI.ID_PLUGIN);
178
			uiPreferences.put(fProfilesKey, val);
177
			uiPreferences.put(fProfilesKey, val);
179
			uiPreferences.putInt(fProfilesVersionKey, fProfileVersioner.getCurrentVersion());
178
			uiPreferences.putInt(fProfilesVersionKey, fProfileVersioner.getCurrentVersion());
180
		} finally {
179
		} catch (IOException e) {
181
			try { stream.close(); } catch (IOException e) { /* ignore */ }
180
			// ignore
182
		}
181
		}
183
	}
182
	}
184
183
Lines 190-197 Link Here
190
			} catch (UnsupportedEncodingException e) {
189
			} catch (UnsupportedEncodingException e) {
191
				bytes= profiles.getBytes();
190
				bytes= profiles.getBytes();
192
			}
191
			}
193
			InputStream is= new ByteArrayInputStream(bytes);
192
			try (InputStream is= new ByteArrayInputStream(bytes)) {
194
			try {
195
				List<Profile> res= readProfilesFromStream(new InputSource(is));
193
				List<Profile> res= readProfilesFromStream(new InputSource(is));
196
				if (res != null) {
194
				if (res != null) {
197
					for (int i= 0; i < res.size(); i++) {
195
					for (int i= 0; i < res.size(); i++) {
Lines 199-206 Link Here
199
					}
197
					}
200
				}
198
				}
201
				return res;
199
				return res;
202
			} finally {
200
			} catch (IOException e) {
203
				try { is.close(); } catch (IOException e) { /* ignore */ }
201
				// ignore
204
			}
202
			}
205
		}
203
		}
206
		return null;
204
		return null;
Lines 215-227 Link Here
215
	 * @throws CoreException
213
	 * @throws CoreException
216
	 */
214
	 */
217
	public List<Profile> readProfilesFromFile(File file) throws CoreException {
215
	public List<Profile> readProfilesFromFile(File file) throws CoreException {
218
		try {
216
		try (final FileInputStream reader= new FileInputStream(file)) {
219
			final FileInputStream reader= new FileInputStream(file);
217
			return readProfilesFromStream(new InputSource(reader));
220
			try {
221
				return readProfilesFromStream(new InputSource(reader));
222
			} finally {
223
				try { reader.close(); } catch (IOException e) { /* ignore */ }
224
			}
225
		} catch (IOException e) {
218
		} catch (IOException e) {
226
			throw createException(e, FormatterMessages.CodingStyleConfigurationBlock_error_reading_xml_message);
219
			throw createException(e, FormatterMessages.CodingStyleConfigurationBlock_error_reading_xml_message);
227
		}
220
		}
Lines 258-271 Link Here
258
	 * @throws CoreException
251
	 * @throws CoreException
259
	 */
252
	 */
260
	public void writeProfilesToFile(Collection<Profile> profiles, File file, String encoding) throws CoreException {
253
	public void writeProfilesToFile(Collection<Profile> profiles, File file, String encoding) throws CoreException {
261
		final OutputStream stream;
254
		try (final OutputStream stream= new FileOutputStream(file)) {
262
		try {
255
			writeProfilesToStream(profiles, stream, encoding, fProfileVersioner);
263
			stream= new FileOutputStream(file);
264
			try {
265
				writeProfilesToStream(profiles, stream, encoding, fProfileVersioner);
266
			} finally {
267
				try { stream.close(); } catch (IOException e) { /* ignore */ }
268
			}
269
		} catch (IOException e) {
256
		} catch (IOException e) {
270
			throw createException(e, FormatterMessages.CodingStyleConfigurationBlock_error_serializing_xml_message);
257
			throw createException(e, FormatterMessages.CodingStyleConfigurationBlock_error_serializing_xml_message);
271
		}
258
		}
(-)a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/correction/SerialVersionHashOperation.java (-4 / +1 lines)
Lines 89-102 Link Here
89
			if (classfileResource == null)
89
			if (classfileResource == null)
90
				return null;
90
				return null;
91
91
92
			InputStream contents= classfileResource.getContents();
92
			try (InputStream contents= classfileResource.getContents()) {
93
			try {
94
				IClassFileReader cfReader= ToolFactory.createDefaultClassFileReader(contents, IClassFileReader.ALL);
93
				IClassFileReader cfReader= ToolFactory.createDefaultClassFileReader(contents, IClassFileReader.ALL);
95
				if (cfReader != null) {
94
				if (cfReader != null) {
96
					return calculateSerialVersionId(cfReader);
95
					return calculateSerialVersionId(cfReader);
97
				}
96
				}
98
			} finally {
99
				contents.close();
100
			}
97
			}
101
			return null;
98
			return null;
102
		} finally {
99
		} finally {
(-)a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/java/hover/JavaSourceHover.java (-9 / +2 lines)
Lines 400-424 Link Here
400
	}
400
	}
401
401
402
	private String removeLeadingComments(String source) {
402
	private String removeLeadingComments(String source) {
403
		final JavaCodeReader reader= new JavaCodeReader();
404
		IDocument document= new Document(source);
403
		IDocument document= new Document(source);
405
		int i;
404
		int i;
406
		try {
405
		try (final JavaCodeReader reader= new JavaCodeReader()) {
407
			reader.configureForwardReader(document, 0, document.getLength(), true, false);
406
			reader.configureForwardReader(document, 0, document.getLength(), true, false);
408
			int c= reader.read();
407
			int c= reader.read();
409
			while (c != -1 && (c == '\r' || c == '\n')) {
408
			while (c != -1 && (c == '\r' || c == '\n')) {
410
				c= reader.read();
409
				c= reader.read();
411
			}
410
			}
412
			i= reader.getOffset();
411
			i= reader.getOffset();
413
			reader.close();
414
		} catch (IOException ex) {
412
		} catch (IOException ex) {
415
			i= 0;
413
			i= 0;
416
		} finally {
414
			JavaPlugin.log(ex);
417
			try {
418
				reader.close();
419
			} catch (IOException ex) {
420
				JavaPlugin.log(ex);
421
			}
422
		}
415
		}
423
416
424
		if (i < 0)
417
		if (i < 0)
(-)a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/javadoc/JavadocContentAccess2.java (-45 / +14 lines)
Lines 759-780 Link Here
759
		Javadoc javadoc= getJavadocNode(member, rawJavadoc);
759
		Javadoc javadoc= getJavadocNode(member, rawJavadoc);
760
760
761
		if (javadoc == null) {
761
		if (javadoc == null) {
762
			Reader contentReader= null;
762
			try (Reader contentReader = JavadocContentAccess.getHTMLContentReader(member, false, false)) {
763
			// fall back to JavadocContentAccess:
763
			// fall back to JavadocContentAccess:
764
			try {
765
				contentReader= JavadocContentAccess.getHTMLContentReader(member, false, false);
766
				if (contentReader != null)
764
				if (contentReader != null)
767
					return getString(contentReader);
765
					return getString(contentReader);
768
			} catch (JavaModelException e) {
766
			} catch (JavaModelException e) {
769
				JavaPlugin.log(e);
767
				JavaPlugin.log(e);
770
			} finally {
768
			} catch (IOException e) {
771
				if (contentReader != null) {
769
				//ignore
772
					try {
773
						contentReader.close();
774
					} catch (IOException e) {
775
						//ignore
776
					}
777
				}
778
			}
770
			}
779
			return null;
771
			return null;
780
		}
772
		}
Lines 2077-2094 Link Here
2077
	}
2069
	}
2078
2070
2079
	private static String getHTMLContent(IJarEntryResource jarEntryResource, String encoding) throws CoreException {
2071
	private static String getHTMLContent(IJarEntryResource jarEntryResource, String encoding) throws CoreException {
2080
		InputStream in= jarEntryResource.getContents();
2072
		try (InputStream in = jarEntryResource.getContents()) {
2081
		try {
2082
			return getContentsFromInputStream(in, encoding);
2073
			return getContentsFromInputStream(in, encoding);
2083
		} finally {
2074
		} catch (IOException e) {
2084
			if (in != null) {
2075
			// ignore
2085
				try {
2076
			return null;
2086
					in.close();
2077
		} 
2087
				} catch (IOException e) {
2088
					//ignore
2089
				}
2090
			}
2091
		}
2092
	}
2078
	}
2093
2079
2094
	private static String getHTMLContentFromAttachedSource(IPackageFragmentRoot root, IPackageFragment packageFragment) throws CoreException {
2080
	private static String getHTMLContentFromAttachedSource(IPackageFragmentRoot root, IPackageFragment packageFragment) throws CoreException {
Lines 2154-2187 Link Here
2154
				} else {
2140
				} else {
2155
					packagedocPath= filePath;
2141
					packagedocPath= filePath;
2156
				}
2142
				}
2157
				ZipFile zipFile= null;
2143
				try (ZipFile zipFile= new ZipFile(file, ZipFile.OPEN_READ)) {
2158
				InputStream in= null;
2159
				try {
2160
					zipFile= new ZipFile(file, ZipFile.OPEN_READ);
2161
					ZipEntry packagedocFile= zipFile.getEntry(packagedocPath);
2144
					ZipEntry packagedocFile= zipFile.getEntry(packagedocPath);
2162
					if (packagedocFile != null) {
2145
					if (packagedocFile != null) {
2163
						in= zipFile.getInputStream(packagedocFile);
2146
						try (InputStream in= zipFile.getInputStream(packagedocFile)) {
2164
						if (encoding == null)
2147
							if (encoding == null)
2165
							encoding= getSourceAttachmentEncoding(root);
2148
								encoding= getSourceAttachmentEncoding(root);
2166
						return getContentsFromInputStream(in, encoding);
2149
							return getContentsFromInputStream(in, encoding);
2150
						}
2167
					}
2151
					}
2168
				} catch (IOException e) {
2152
				} catch (IOException e) {
2169
					throw new CoreException(new Status(IStatus.ERROR, JavaPlugin.getPluginId(), e.getMessage(), e));
2153
					throw new CoreException(new Status(IStatus.ERROR, JavaPlugin.getPluginId(), e.getMessage(), e));
2170
				} finally {
2171
					try {
2172
						if (in != null) {
2173
							in.close();
2174
						}
2175
					} catch (IOException e) {
2176
						//ignore
2177
					}
2178
					try {
2179
						if (zipFile != null) {
2180
							zipFile.close();//this will close the InputStream also
2181
						}
2182
					} catch (IOException e) {
2183
						//ignore
2184
					}
2185
				}
2154
				}
2186
			}
2155
			}
2187
		}
2156
		}
(-)a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/spelling/SpellCheckEngine.java (-8 / +3 lines)
Lines 426-439 Link Here
426
					return;
426
					return;
427
427
428
				final URL url= new URL("file", null, filePath); //$NON-NLS-1$
428
				final URL url= new URL("file", null, filePath); //$NON-NLS-1$
429
				InputStream stream= url.openStream();
429
				try (InputStream stream= url.openStream()) {
430
				if (stream != null) {
430
					fUserDictionary= new PersistentSpellDictionary(url);
431
					try {
431
					fChecker.addDictionary(fUserDictionary);
432
						fUserDictionary= new PersistentSpellDictionary(url);
433
						fChecker.addDictionary(fUserDictionary);
434
					} finally {
435
						stream.close();
436
					}
437
				}
432
				}
438
			} catch (MalformedURLException exception) {
433
			} catch (MalformedURLException exception) {
439
				// Do nothing
434
				// Do nothing
(-)a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/spelling/engine/AbstractSpellDictionary.java (-30 / +24 lines)
Lines 603-612 Link Here
603
			 return fLoaded;
603
			 return fLoaded;
604
604
605
		if (url != null) {
605
		if (url != null) {
606
			InputStream stream= null;
607
			int line= 0;
606
			int line= 0;
608
			try {
607
			try (InputStream stream= url.openStream()) {
609
				stream= url.openStream();
610
				if (stream != null) {
608
				if (stream != null) {
611
					String word= null;
609
					String word= null;
612
610
Lines 614-644 Link Here
614
					CharsetDecoder decoder= Charset.forName(getEncoding()).newDecoder();
612
					CharsetDecoder decoder= Charset.forName(getEncoding()).newDecoder();
615
					decoder.onMalformedInput(CodingErrorAction.REPORT);
613
					decoder.onMalformedInput(CodingErrorAction.REPORT);
616
					decoder.onUnmappableCharacter(CodingErrorAction.REPORT);
614
					decoder.onUnmappableCharacter(CodingErrorAction.REPORT);
617
					final BufferedReader reader= new BufferedReader(new InputStreamReader(stream, decoder));
615
					try (final BufferedReader reader= new BufferedReader(new InputStreamReader(stream, decoder))) {
618
616
	
619
					boolean doRead= true;
617
						boolean doRead= true;
620
					while (doRead) {
618
						while (doRead) {
621
						try {
619
							try {
622
							word= reader.readLine();
620
								word= reader.readLine();
623
						} catch (MalformedInputException ex) {
621
							} catch (MalformedInputException ex) {
624
							// Tell the decoder to replace malformed input in order to read the line.
622
								// Tell the decoder to replace malformed input in order to read the line.
625
							decoder.onMalformedInput(CodingErrorAction.REPLACE);
623
								decoder.onMalformedInput(CodingErrorAction.REPLACE);
626
							decoder.reset();
624
								decoder.reset();
627
							word= reader.readLine();
625
								word= reader.readLine();
628
							decoder.onMalformedInput(CodingErrorAction.REPORT);
626
								decoder.onMalformedInput(CodingErrorAction.REPORT);
629
627
	
630
							String message= Messages.format(JavaUIMessages.AbstractSpellingDictionary_encodingError, new String[] { word, decoder.replacement(), BasicElementLabels.getURLPart(url.toString()) });
628
								String message= Messages.format(JavaUIMessages.AbstractSpellingDictionary_encodingError, new String[] { word, decoder.replacement(), BasicElementLabels.getURLPart(url.toString()) });
631
							IStatus status= new Status(IStatus.ERROR, JavaUI.ID_PLUGIN, IStatus.OK, message, ex);
629
								IStatus status= new Status(IStatus.ERROR, JavaUI.ID_PLUGIN, IStatus.OK, message, ex);
632
							JavaPlugin.log(status);
630
								JavaPlugin.log(status);
633
631
	
632
								doRead= word != null;
633
								continue;
634
							}
634
							doRead= word != null;
635
							doRead= word != null;
635
							continue;
636
							if (doRead)
637
								hashWord(word);
636
						}
638
						}
637
						doRead= word != null;
639
						return true;
638
						if (doRead)
639
							hashWord(word);
640
					}
640
					}
641
					return true;
642
				}
641
				}
643
			} catch (FileNotFoundException ex) {
642
			} catch (FileNotFoundException ex) {
644
				String urlString= url.toString();
643
				String urlString= url.toString();
Lines 660-670 Link Here
660
					JavaPlugin.log(exception);
659
					JavaPlugin.log(exception);
661
			} finally {
660
			} finally {
662
				fMustLoad= false;
661
				fMustLoad= false;
663
				try {
664
					if (stream != null)
665
						stream.close();
666
				} catch (IOException x) {
667
				}
668
			}
662
			}
669
		}
663
		}
670
		return false;
664
		return false;
(-)a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/spelling/engine/PersistentSpellDictionary.java (-21 / +11 lines)
Lines 49-69 Link Here
49
		if (isCorrect(word))
49
		if (isCorrect(word))
50
			return;
50
			return;
51
51
52
		FileOutputStream fileStream= null;
52
		Charset charset= Charset.forName(getEncoding());
53
		try {
53
		ByteBuffer byteBuffer= charset.encode(word + "\n"); //$NON-NLS-1$
54
			Charset charset= Charset.forName(getEncoding());
54
		int size= byteBuffer.limit();
55
			ByteBuffer byteBuffer= charset.encode(word + "\n"); //$NON-NLS-1$
55
		final byte[] byteArray;
56
			int size= byteBuffer.limit();
56
		if (byteBuffer.hasArray())
57
			final byte[] byteArray;
57
			byteArray= byteBuffer.array();
58
			if (byteBuffer.hasArray())
58
		else {
59
				byteArray= byteBuffer.array();
59
			byteArray= new byte[size];
60
			else {
60
			byteBuffer.get(byteArray);
61
				byteArray= new byte[size];
61
		}
62
				byteBuffer.get(byteArray);
62
		try (FileOutputStream fileStream= new FileOutputStream(fLocation.getPath(), true)) {
63
			}
64
65
			fileStream= new FileOutputStream(fLocation.getPath(), true);
66
67
			// Encoding UTF-16 charset writes a BOM. In which case we need to cut it away if the file isn't empty
63
			// Encoding UTF-16 charset writes a BOM. In which case we need to cut it away if the file isn't empty
68
			int bomCutSize= 0;
64
			int bomCutSize= 0;
69
			if (!isEmpty() && "UTF-16".equals(charset.name())) //$NON-NLS-1$
65
			if (!isEmpty() && "UTF-16".equals(charset.name())) //$NON-NLS-1$
Lines 73-84 Link Here
73
		} catch (IOException exception) {
69
		} catch (IOException exception) {
74
			JavaPlugin.log(exception);
70
			JavaPlugin.log(exception);
75
			return;
71
			return;
76
		} finally {
77
			try {
78
				if (fileStream != null)
79
					fileStream.close();
80
			} catch (IOException e) {
81
			}
82
		}
72
		}
83
73
84
		hashWord(word);
74
		hashWord(word);
(-)a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/wizards/ClassPathDetector.java (-12 / +5 lines)
Lines 184-202 Link Here
184
		for (Iterator<IResource> iter= fClassFiles.iterator(); iter.hasNext();) {
184
		for (Iterator<IResource> iter= fClassFiles.iterator(); iter.hasNext();) {
185
			IFile file= (IFile) iter.next();
185
			IFile file= (IFile) iter.next();
186
			IClassFileReader reader= null;
186
			IClassFileReader reader= null;
187
			InputStream content= null;
187
			try (InputStream content= file.getContents()) {
188
			try {
189
				content= file.getContents();
190
				reader= ToolFactory.createDefaultClassFileReader(content, IClassFileReader.CLASSFILE_ATTRIBUTES);
188
				reader= ToolFactory.createDefaultClassFileReader(content, IClassFileReader.CLASSFILE_ATTRIBUTES);
191
			} finally {
189
			} catch (IOException e) {
192
				try {
190
				throw new CoreException(new Status(IStatus.ERROR, JavaPlugin.getPluginId(), IStatus.ERROR,
193
					if (content != null)
191
					Messages.format(NewWizardMessages.ClassPathDetector_error_closing_file, BasicElementLabels.getPathLabel(file.getFullPath(), false)),
194
						content.close();
192
					e));
195
				} catch (IOException e) {
196
					throw new CoreException(new Status(IStatus.ERROR, JavaPlugin.getPluginId(), IStatus.ERROR,
197
						Messages.format(NewWizardMessages.ClassPathDetector_error_closing_file, BasicElementLabels.getPathLabel(file.getFullPath(), false)),
198
						e));
199
				}
200
			}
193
			}
201
			if (reader == null) {
194
			if (reader == null) {
202
				continue; // problematic class file
195
				continue; // problematic class file
(-)a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/ui/JavadocContentAccess.java (+1 lines)
Lines 164-169 Link Here
164
		return getHTMLContentReader(member, allowInherited, false);
164
		return getHTMLContentReader(member, allowInherited, false);
165
	}
165
	}
166
166
167
	@SuppressWarnings("resource")
167
	private static Reader findDocInHierarchy(IMethod method, boolean isHTML, boolean useAttachedJavadoc) throws JavaModelException {
168
	private static Reader findDocInHierarchy(IMethod method, boolean isHTML, boolean useAttachedJavadoc) throws JavaModelException {
168
		/*
169
		/*
169
		 * Catch ExternalJavaProject in which case
170
		 * Catch ExternalJavaProject in which case
(-)a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/ui/jarpackager/JarWriter.java (-10 / +1 lines)
Lines 122-130 Link Here
122
	 */
122
	 */
123
	public void write(IFile resource, IPath destinationPath) throws CoreException {
123
	public void write(IFile resource, IPath destinationPath) throws CoreException {
124
		ByteArrayOutputStream output= new ByteArrayOutputStream();
124
		ByteArrayOutputStream output= new ByteArrayOutputStream();
125
		BufferedInputStream contentStream= null;
125
		try (BufferedInputStream contentStream= new BufferedInputStream(resource.getContents(false))) {
126
		try {
127
			contentStream= new BufferedInputStream(resource.getContents(false));
128
			int chunkSize= 4096;
126
			int chunkSize= 4096;
129
			byte[] readBuffer= new byte[chunkSize];
127
			byte[] readBuffer= new byte[chunkSize];
130
			int count;
128
			int count;
Lines 132-144 Link Here
132
				output.write(readBuffer, 0, count);
130
				output.write(readBuffer, 0, count);
133
		} catch (IOException ex) {
131
		} catch (IOException ex) {
134
			throw JarPackagerUtil.createCoreException(ex.getLocalizedMessage(), ex);
132
			throw JarPackagerUtil.createCoreException(ex.getLocalizedMessage(), ex);
135
		} finally {
136
			try {
137
				if (contentStream != null)
138
					contentStream.close();
139
			} catch (IOException ex) {
140
				throw JarPackagerUtil.createCoreException(ex.getLocalizedMessage(), ex);
141
			}
142
		}
133
		}
143
		try {
134
		try {
144
			IPath fileLocation= resource.getLocation();
135
			IPath fileLocation= resource.getLocation();
(-)a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/ui/jarpackager/JarWriter2.java (-19 / +2 lines)
Lines 169-192 Link Here
169
		// Set modification time
169
		// Set modification time
170
		newEntry.setTime(lastModified);
170
		newEntry.setTime(lastModified);
171
171
172
		InputStream contentStream = resource.getContents(false);
172
		try (InputStream contentStream = resource.getContents(false)) {
173
174
		try {
175
			fJarOutputStream.putNextEntry(newEntry);
173
			fJarOutputStream.putNextEntry(newEntry);
176
			int count;
174
			int count;
177
			while ((count= contentStream.read(readBuffer, 0, readBuffer.length)) != -1)
175
			while ((count= contentStream.read(readBuffer, 0, readBuffer.length)) != -1)
178
				fJarOutputStream.write(readBuffer, 0, count);
176
				fJarOutputStream.write(readBuffer, 0, count);
179
		} finally  {
180
			if (contentStream != null)
181
				contentStream.close();
182
183
			/*
184
			 * Commented out because some JREs throw an NPE if a stream
185
			 * is closed twice. This works because
186
			 * a) putNextEntry closes the previous entry
187
			 * b) closing the stream closes the last entry
188
			 */
189
			// fJarOutputStream.closeEntry();
190
		}
177
		}
191
	}
178
	}
192
179
Lines 201-218 Link Here
201
	 * @throws	CoreException 	if the resource can-t be accessed
188
	 * @throws	CoreException 	if the resource can-t be accessed
202
	 */
189
	 */
203
	private void calculateCrcAndSize(JarEntry jarEntry, IFile resource, byte[] readBuffer) throws IOException, CoreException {
190
	private void calculateCrcAndSize(JarEntry jarEntry, IFile resource, byte[] readBuffer) throws IOException, CoreException {
204
		InputStream contentStream = resource.getContents(false);
205
		int size = 0;
191
		int size = 0;
206
		CRC32 checksumCalculator= new CRC32();
192
		CRC32 checksumCalculator= new CRC32();
207
		int count;
193
		int count;
208
		try {
194
		try (InputStream contentStream = resource.getContents(false)) {
209
			while ((count= contentStream.read(readBuffer, 0, readBuffer.length)) != -1) {
195
			while ((count= contentStream.read(readBuffer, 0, readBuffer.length)) != -1) {
210
				checksumCalculator.update(readBuffer, 0, count);
196
				checksumCalculator.update(readBuffer, 0, count);
211
				size += count;
197
				size += count;
212
			}
198
			}
213
		} finally {
214
			if (contentStream != null)
215
				contentStream.close();
216
		}
199
		}
217
		jarEntry.setSize(size);
200
		jarEntry.setSize(size);
218
		jarEntry.setCrc(checksumCalculator.getValue());
201
		jarEntry.setCrc(checksumCalculator.getValue());
(-)a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/ui/jarpackager/JarWriter3.java (-26 / +3 lines)
Lines 313-340 Link Here
313
			}
313
			}
314
		});
314
		});
315
		File file= null;
315
		File file= null;
316
		OutputStream output= null;
317
		try {
316
		try {
318
			file= File.createTempFile("history", null); //$NON-NLS-1$
317
			file= File.createTempFile("history", null); //$NON-NLS-1$
319
			output= new BufferedOutputStream(new FileOutputStream(file));
318
			try (OutputStream output= new BufferedOutputStream(new FileOutputStream(file))) {
320
			try {
321
				RefactoringCore.getHistoryService().writeRefactoringDescriptors(proxies, output, RefactoringDescriptor.NONE, false, monitor);
319
				RefactoringCore.getHistoryService().writeRefactoringDescriptors(proxies, output, RefactoringDescriptor.NONE, false, monitor);
322
				try {
323
					output.close();
324
					output= null;
325
				} catch (IOException exception) {
326
					// Do nothing
327
				}
328
				writeMetaData(data, file, path);
329
			} finally {
330
				if (output != null) {
331
					try {
332
						output.close();
333
					} catch (IOException exception) {
334
						// Do nothing
335
					}
336
				}
337
			}
320
			}
321
			writeMetaData(data, file, path);
338
		} finally {
322
		} finally {
339
			if (file != null)
323
			if (file != null)
340
				file.delete();
324
				file.delete();
Lines 470-487 Link Here
470
			JarPackagerUtil.calculateCrcAndSize(entry, new BufferedInputStream(new FileInputStream(file)), buffer);
454
			JarPackagerUtil.calculateCrcAndSize(entry, new BufferedInputStream(new FileInputStream(file)), buffer);
471
		}
455
		}
472
		entry.setTime(System.currentTimeMillis());
456
		entry.setTime(System.currentTimeMillis());
473
		final InputStream stream= new BufferedInputStream(new FileInputStream(file));
457
		try (final InputStream stream= new BufferedInputStream(new FileInputStream(file))) {
474
		try {
475
			fJarOutputStream.putNextEntry(entry);
458
			fJarOutputStream.putNextEntry(entry);
476
			int count;
459
			int count;
477
			while ((count= stream.read(buffer, 0, buffer.length)) != -1)
460
			while ((count= stream.read(buffer, 0, buffer.length)) != -1)
478
				fJarOutputStream.write(buffer, 0, count);
461
				fJarOutputStream.write(buffer, 0, count);
479
		} finally {
480
			try {
481
				stream.close();
482
			} catch (IOException exception) {
483
				// Do nothing
484
			}
485
		}
462
		}
486
	}
463
	}
487
}
464
}

Return to bug 509247